我是 C 编程语言的初学者,因此我需要对此进行解释:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int NUM[10];
int i,index;
for(i=0 ; i<8 ; i++){
NUM[index]=i;
index++;
}
printf("this is the number %d\n\n",NUM);
return 0;
}
这是输出:
this is the number 6356704
为什么控制台中的数字不正确?
最佳答案
printf("this is the number %d\n\n",NUM);
将 NUM
传递给 printf
进行格式化%d
转换说明符。
NUM
是一个数组。在此使用中,它会自动转换为其第一个元素的地址。 %d
期望传递一个 int
。地址不是 int
。由于这种不匹配,C 标准未定义此代码的行为。最好的情况是,printf
会打印十进制格式的地址。
要打印数组的元素,您必须编写一个循环来打印每个元素,例如将 NUM[i]
传递给 printf
以使用 进行格式化>%d
。您可以使用:
for (int i = 0; i < 8; ++i)
printf("NUM[%d] = %d.\n", i, NUM[i]);
关于c - C语言中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58044981/