简体   繁体   中英

String Array Keeps Printing Last Entry in C

I don't quite understand why when I run the code, inputting with 5 different strings, it prints string[0] as the last string that I enter:

for example, if I input:

yes
no

it would print:


Check yes
yes
yes
Check no
no
no

even for index=0

int main(void) {
   char *string[5];
   char entered[11];
   for(int j = 0; j < 5; j++) {
     scanf("%s", &entered);
     string[j] = entered;
     printf("Check %s\n",entered);    
     printf("%s\n",string[j]); 
     printf("%s\n",string[0]); 
       }
   return 0;
 }

My intention is to save each string entry into the array.

So for my example, I want:


Check yes
yes
yes
Check no
no
yes

I am not allowed to use malloc...etc.

This line:

     string[j] = entered;

does not copy characters from entered to string[j] ; rather, it sets string[j] to point to the memory location of the entered array.

You need to allocate memory for the strings in your string array, by writing (eg):

char string[5][11];

instead of

char *string[5];

and then you need to copy characters from entered from string[j] by writing (eg):

     strcmp(string[j], entered);

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