[英]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]
entered
的string[j]
:
strcmp(string[j], entered);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.