c - Initializing pointer to an array of strings -
c - Initializing pointer to an array of strings -
char *arr[100];
how correctly initialize this? there other problem line? i'm new c , programming in general , having hard time understanding this.
this rest of code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <cstdlib> int main () { char ans[100]; int count; count=0; char *arr[100]; char *srtarr[100]; while(count<100) { if(strcmp(ans,"done\n")!=0) { printf("enter names when done type done:"); fgets(ans,100,stdin); arr[count]=strdup(ans); } printf("%s",arr[count]); count++; } system("pause"); homecoming 0; }
the programme crashing since have logic error.
take @ while loop.
while(count<100) { if(strcmp(ans,"done\n")!=0) { printf("enter names when done type done:"); fgets(ans,100,stdin); arr[count]=strdup(ans); } printf("%s",arr[count]); count++; }
let's user entered
done
as first line of input. nil gets set arr[1]
. @ time, arr[1]
not initialized. points garbage. lead undefined behavior in line
printf("%s",arr[count]);
you need little rearrangement of while
loop.
while(count<100) { printf("enter names when done type done:"); fgets(ans,100,stdin); if(strcmp(ans,"done\n") ==0 ) { break; } arr[count]=strdup(ans); printf("%s",arr[count]); count++; }
c arrays pointers
Comments
Post a Comment