Trying to store input into array of strings with following code:
#include <stdio.h>
#include <string.h>
int main()
{
int noOfStrings;
printf("Enter no of strings: ");
scanf("%d", &noOfStrings);
char *string[noOfStrings];
for(int i=0; i<noOfStrings; i++){
printf("\nEnter string %d: ", i);
scanf("%s\n",string[i]);
}
return 0;
}
-----------------------------------------------------------------------------
Console:
Enter no of strings: 3
Enter string 0: abc
Enter string 1: def
Enter string 2: ghi
Segmentation fault (core dumped)
...Program finished with exit code 139
Press ENTER to exit console.
-----------------------------------------------------------------------------
I am not able to figure out why this is failing.
I also Tried following code with fixed size array.
#include <stdio.h>
#include <string.h>
int main()
{
int noOfStrings;
printf("Enter no of strings: ");
scanf("%d", &noOfStrings);
char string[noOfStrings][5];
for(int i=0; i<noOfStrings; i++){
printf("\nEnter string %d: ", i);
scanf("%s\n",string[i]);
}
printf("\nPrinting Stored Strings");
for(int i=0; i<noOfStrings; i++){
printf("\nEnter string %d: ", i);
printf("%s\n",string[i]);
}
return 0;
}
-----------------------------------------------------------------------------
Console:
Enter no of strings: 3
Enter string 0: abc
def
Enter string 1: ghi
Enter string 2: jkl
Printing Stored Strings
Enter string 0: abc
Enter string 1: def
Enter string 2: ghi
...Program finished with exit code 0
Press ENTER to exit console.
After entering 1st string ('abc') There was no prompt for 2nd string, so proceeded by entering 'def'. Followed by 2 more strings. Notice that string 'jkl' is not printed.
Please tell me what i am missing in these 2 cases?
Thanks.
*scanf()and don't check the return value, that's relying on the user to not invoke undefined behaviour of your program. Don't do that.