int main()
{
int i = 0;
char *string[2][5], trunkcode[50];
while (i <= 1)
{
if(i == 0)
strcpy(trunkcode,"test0");
else if(i == 1)
strcpy(trunkcode,"test1");
string[i][0] = trunkcode;
printf("trunkcode %s\n",string[i][0]);
++i;
}
printf("\n");
printf("trunkcode %s\n",string[0][0]);
printf("trunkcode %s\n",string[1][0]);
return 0;
}输出:
中继码test0
中继码test1
中继码test1
中继码test1
为什么输出不是
中继码test0
中继码test1
中继码test0
中继码test1
发布于 2020-09-09 05:59:46
只有一个trunkcode数组。string[0][0]和string[1][0]都包含指向同一数组的指针。您将数组的内容替换为strcpy()代码,因此在循环结束时,数组包含test1,并且两个指针都指向该内容。
您不需要trunkcode数组。只需使string成为一个二维数组的字符,而不是指针。
int main()
{
int i = 0;
char string[2][50];
while (i <= 1)
{
if(i == 0)
strcpy(string[i],"test0");
else if(i == 1)
strcpy(string[i],"test1");
printf("trunkcode %s\n",string[i]);
++i;
}
printf("\n");
printf("trunkcode %s\n",string[0]);
printf("trunkcode %s\n",string[1]);
return 0;
}发布于 2020-09-09 06:13:30
下面是您的程序中发生的事情(如下面的代码所示),
int main(void)
{
int i = 0;
char *string[2][5], trunkcode[50];
while (i <= 1)
{
if(i == 0)
strcpy(trunkcode,"test0"); // truncode would contain test0 when i = 0
else if(i == 1)
strcpy(trunkcode,"test1"); // truncode would contain test1 when i = 1
string[i][0] = trunkcode; // points to value stored in truncode
printf("trunkcode %s\n",string[i][0]); // test0 is printed at i = 0 and test1 at i = 1
// above line prints whatever string[i][0] points to, which is 'current value' of truncode.
++i;
}
printf("\n");
printf("trunkcode %s\n",string[0][0]); // string[0][0] now points to last value of truncode (test1)
printf("trunkcode %s\n",string[1][0]); // string [1][1] also points to last value of truncode (test1)
return 0;
}发布于 2020-09-09 06:37:50
我相信你写的不是你想要的。
您将字符串声明为:
char *string[2][5];也许写起来更清晰
char* string[2][5];当你这样写的时候,你会明白什么是string:一个指向char的2x5指针数组。只是一些指点。因此,在使用之前,您必须为10个指针中的任何一个分配内存,或者将它们指向已经分配的对象。
你已经有了
char trunkcode[50];一个50个字符的数组。并且它是代码中唯一分配的char。它一次只能包含一个值,从trunkcode[0]到trunkcode[49],最多50 char。
string[i][0] = trunkcode; // points to value stored in truncode在评论中写下它并不意味着它是真的。trunkcode is char[50] string[][] is char*。这个赋值使string[i][0]指向trunkcode的地址,你可以写&trunkcode[0],或者只写trunkcode。
当您通过strcpy()更改trunkcode时,您将更改string[0][0]所指向的内容。也是string[1][0]指出的,因为两个都指向trunkcode
https://stackoverflow.com/questions/63801669
复制相似问题