简体   繁体   中英

Reading a string into an 2D array of strings in C

Suppose I have a 2D array of string in the form ar[i][j], where i refers to the ith string in the array and j is the specific index of a character in that string. I wish to make a function that gets the size from the user (number of names), and let them input names separated by a whitespace. Here's my attempt at the function:

void readNames(char nameptr[][80], int *size)
{
   int i;
   char dummychar;

   printf("Enter size:\n");
   scanf("%d", size);
   scanf("%c", &dummychar);
   printf("Enter %d names:\n", *size);
   for ( i = 0; i < size; i++)
   {
       scanf("%s", &nameptr[i]);
   }
   printf("Test?");

}

Here's a sample input:

Enter size:
5
Enter 5 names:
Sam Paul John Mary Nick

After this, the array that was passed into the function, nameptr, should have the following values:

nameptr[0] = "Sam\0"
nameptr[1] = "Paul\0"
nameptr[2] = "John\0"
nameptr[3] = "Mary\0"
nameptr[4] = "Nick\0"

However, something seems to be wrong at the last scanf step, as the program simply times out and doesn't print the last test statement. I'm not sure if it's a syntax error, and I'm not sure how to scanf properly into an 2D array of strings in this case. Any help and insights are appreciated, thank you very much.

It turns out the mistake is in the line:

   for ( i = 0; i < size; i++)

I have passed the size into the function via a pointer, so it should be

for ( i = 0; i < *size; i++)

and the function works as expected. Thanks for reading.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM