简体   繁体   English

字符串数组在C中保留打印最后一个条目

[英]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: 我不太明白为什么当我运行代码时,输​​入5​​个不同的字符串,它打印字符串[0]作为我输入的最后一个字符串:

for example, if I input: 例如,如果我输入:

yes
no 没有

it would print: 它会打印:


Check yes 检查是的
yes
yes
Check no 检查号码
no 没有
no 没有

even for index=0 甚至索引= 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. 我不被允许使用malloc等。

This line: 这一行:

     string[j] = entered;

does not copy characters from entered to string[j] ; 不会将entered字符复制到string[j] ; rather, it sets string[j] to point to the memory location of the entered array. 相反,它将string[j]为指向entered数组的内存位置。

You need to allocate memory for the strings in your string array, by writing (eg): 您需要通过编写(例如)来为string数组中的string分配内存:

char string[5][11];

instead of 代替

char *string[5];

and then you need to copy characters from entered from string[j] by writing (eg): 然后你需要通过写(例如)来复制从string[j] enteredstring[j]

     strcmp(string[j], entered);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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