kype
kype

Reputation: 595

Storing strings in a ragged array

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

Upvotes: 0

Views: 1515

Answers (2)

Jeremy Friesner
Jeremy Friesner

Reputation: 73061

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:

for( count = 0 ; count <= num ; count++)
{
   printf("Enter a name: ");
   char temp[1024];
   scanf( "%s" , temp);
   myNames[i] = strdup(temp);
   fflush(stdin);
}

... 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.

Upvotes: 1

Asha
Asha

Reputation: 11232

char *myNames[10]; creates 10 character pointers which point to some random memory location. When you do scanf( "%s" , myNames[count]); you are trying to write to this memory location which causes access violation. You need to allocate memory for the strings and then make these pointers point to the allocated memory by doing something like this: myNames[0] = malloc(10); which allocates space for 10 characters. Note that, once processing is done you need to deallocate memory by doing free(myNames[0]);.

Upvotes: 0

Related Questions