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.
In the first case, you're defining an array of pointers:
char *string[noOfStrings];
However, these pointers are uninitialized. When you then attempt to use scanf
, you dereference these invalid pointers. Doing so invokes undefined behavior , which in this case causes a crash.
Your second case fixes this by using a 2D array of characters big enough to hold the strings you input. But you get stuck because of your scanf
format:
scanf("%s\n",string[i]);
The \\n
in the format string matches any number of whitespace characters , so the function won't return until you enter a non-whitespace character. You can fix this by removing \\n
from the format string.
scanf("%s",string[i]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.