#include <stdio.h>
int main () {
int n[ 10 ] = {002535}; /* n is an array of 10 integers */
int j;
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
上面的代码运行,并返回等于1373你能解释一下这第一个元素? 我无法理解后面的数字之所以被提供的整数由于改变填充。
输出出来是以下行。
Element[0] = 1373
Element[1] = 0
...
Element[9] = 0
在你的程序中,要初始化数组n
-
int n[ 10 ] = {002535};
数002535被解释为是因为前导零的八进制数。 所以,这将分配八进制值002535
到n[0]
中的阵列,即第0个位置n
数组元素和其余部分将与被初始化0
。
在for
循环,您正在使用的格式说明在打印%d
。
的002535八进制值的十进制值是1373这就是为什么你得到Element [0]
为1373。
如果你要打印的八进制数作为输出,使用%o
格式说明:
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %o\n", j, n[j] );
如果你想十进制2535作为数组的第一个元素n
,删除前导零:
int n[ 10 ] = {2535};
一个整数文字开始0
被解释为一个八进制数。 而02535
的八进制相当于十进制1373
文章来源: Initializing an array in c with same numbers leads to different values [duplicate]