-
Segmentation Fault
I am getting a core dump when I try scanning in the values. Please help.
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char *strings[50];
int amnt;
printf("Enter the number of strings (0 to 50)\n> ");
scanf("%d",&amnt);
printf("Enter %d strings on separate lines\n",amnt);
int i =0;
for (i=0;i<amnt;i++)
{
scanf("\n%s",strings[i]);
}
-
For starters, you never allocated any memory for the strings.
-
Just because you have a pointer somewhere, doesn't mean you own the memory it is pointing to. In this case, you have 50 pointers that don't point anywhere, but you try to use them anyway. You will need memory for each of those pointers (either malloc in a loop, or a 2D character array seem like your options here).
-
What you will need to do is allocate space for your pointer, say malloc for 25 chars, right before your scanf assignment.
To check that your strings were inserted, you can create another 'for loop' to cycle through your array of strings.
Then you will need another for loop to free those malloc calls, or you will cause a memory leak further on down the road......lots of fun.