[英]Why do my integer array elements contain the wrong values when I assign it character values in C and how can I fix this?
I wrote the following code: 我写了以下代码:
#include <stdio.h>
#include <string.h>
int main()
{
char *string = "abcd";
int i;int j;
int array[5];
for(i=0; i<strlen(string); i++)
array[i] = string[i];
for(j=0; j<4; j++)
printf("array[i] %d\n",array[i]);
array[0] = string[0];
printf("array[0] %d\n",array[0]);
return 0;
}
I got the following output: 我得到以下输出:
array[i] 4195888
array[i] 4195888
array[i] 4195888
array[i] 4195888
array[0] 97
I thought the output would be: 我认为输出将是:
array[i] 97
array[i] 98
array[i] 99
array[i] 100
array[0] 97
If this assignment: 如果此作业:
array[0] = string[0];
assigns 97 to array[0], then why doing similar assignments within the loop, produces a different output, and how can I fix my code so that the output would look as I expected it to be? 将97分配给array [0],那么为什么要在循环中进行类似的分配,产生不同的输出,又该如何修复我的代码,以使输出看起来像我期望的那样?
The problem is mismatched index values. 问题是索引值不匹配。
for(j=0; j<4; j++)
printf("array[i] %d\n",array[i]);
should be 应该
for(j=0; j<4; j++) // j is the loop control variable
printf("array[j] %d\n",array[j]); // so, use j as index here
Otherwise, what happens is you use the last value of i
as index, which here, is an attempt to access uninitialized element (ie, array[4]
) which contains indeterminate value. 否则,将使用
i
的最后一个值作为索引,这是在尝试访问包含不确定值的未初始化元素(即array[4]
)。 This invokes undefined behavior . 这会调用未定义的行为 。
To be on safe side, you better initialize the local variables to your function. 为了安全起见,最好将局部变量初始化为函数。
As already pointed out, your printf loop is on j but you are using i as the index into the array, whereas you should index using j. 如前所述,您的printf循环在j上,但是您将i用作数组的索引,而应该使用j进行索引。 You also have j hardcoded within the printf, and it should be %d and then filled in with j.
您还已经在printf中对j进行了硬编码,应该将其%d然后用j填充。
#include <stdio.h>
#include <string.h>
int main()
{
char *string = "abcd";
int i;int j;
int array[5];
for(i=0; i<strlen(string); i++)
array[i] = string[i];
for(j=0; j<4; j++)
printf("array[%d] %d\n",j,array[j]);
array[0] = string[0];
printf("array[0] %d\n",array[0]);
return 0;
}
Then your output will be as expected: 然后您的输出将如预期的那样:
array[0] 97
array[1] 98
array[2] 99
array[3] 100
array[0] 97
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.