can i use fgets for accepting strings in character pointer array instead of scanf [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



can i use fgets for accepting strings in character pointer array instead of scanf [duplicate]



This question already has an answer here:



Although the below code is working fine.But its showing "segmentation fault" when i am trying to accept the strings using fgets as i want to store strings which might contain spaces.How to accept strings (which might contain spaces)
in character pointer array


int main()
char* nm[5];
char* st;
for(int i=0;i<5;i++)
//fgets(nm[i],30,stdin);
scanf("%ms",&nm[i]);
for(int i=0;i<5;i++)
printf("%sn",nm[i]);
return 0;



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




1 Answer
1



nm is a pointer to 5 chars not a pointer to 5 strings, so &nm[2] is the address of the 3rd char in nm. If you change nm to be


char* nm[5][50];



you will have an array of 5 x 50 chars. That should stop the segfault.





Neil please check this link stackoverflow.com/a/50667860/10212490.I think nm[2] points to the base address of 3rd string in the array
– NIKITA AGARWAL
Aug 12 at 7:26





nm is not a pointer to 5 chars, but an array of 5 pointers to char.
– David Bowling
Aug 12 at 8:37


nm


char


char





This answer is wrong. Even the analysis it gives is wrong.
– alk
Aug 12 at 9:41






BTW, "a pointer to 5 chars" would be defined as char (*pointer_to_array_of_5_char)[5];
– alk
Aug 12 at 9:43



char (*pointer_to_array_of_5_char)[5];





I knew my c was rusty but I didn't think it was that bad 😁
– Neil
Aug 12 at 9:46

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard