Im trying to store some user-input names in a ragged array. However i get an error during run-time and im trying to figure out what has gone wrong.
My code:
int num, count, i;
char *myNames[10];
printf("Enter the number of names: ");
scanf( "%d" , &num);
fflush(stdin);
// Ask user to input the name
for( count = 0 ; count <= num ; count++)
{
printf("Enter a name: ");
scanf( "%s" , myNames[count]);
fflush(stdin);
}
// To check if names are stored correctly
printf("%s", *myNames[1]);
return 0;
}
Grateful if anyone can share some help, or at least point me in the right direction. Thanks
You need to allocate space for the strings themselves; currently you only allocate an array of 10 pointers, but they never actually point to any valid memory; hence the error that you get when scanf() tries to write into them.
Of course, in order to allocate the right amount of space for a string you need to know how many characters are in the string, which is a bit of a chicken-and-egg problem; you should probably use one stack-allocated array to let scanf() write into and then strdup() that, like this:
… and of course if you wanted your program to be 100% correct and avoid a memory leak, you’d need to free() each of the 10 strings before returning, but if this is just a toy program you can ignore that and just let the OS deal with cleaning up.