小C计划

时间:2014-12-30 18:22:19

标签: c

有人可以解释输出吗

int main()
{
    int a[2][2]={{1,2},{1,2}};

    printf("a[0]:  %d\n",a[0]);
    printf("a[1]:  %d\n",a[1]);
    printf("Diff:  %d\n",a[1] - a[0]);

    return 0;
}

输出:

  

a [0]: - 214886704
  a [1]: - 214886696
  差异:2

3 个答案:

答案 0 :(得分:4)

您正在尝试打印数组的地址,而不是值。使用a[i][j]访问二维数组的元素。

你应该提高你的编译器的警告级别,它会给你一个关于你做错的明确警告:

lol.c:5:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
lol.c:6:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
 printf("a[1]:  %d\n",a[0]);
 ^
lol.c:7:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
 printf("Diff:  %d\n",a[1] - a[0]);
 ^

答案 1 :(得分:1)

为了访问2D数组中的元素,您需要提供行和列

a[0][0] and a[0][1]

实际上a[0]会为您提供数组的地址。以下代码可能会为您提供使用数组地址

尝试执行的操作
#include <stdio.h>
int main()
{
    int a[2][2]={{1,2},{1,2}};

    printf("a[0]:  %p\n",(void *)a[0]); /* Address of first row */
    printf("a[1]:  %p\n",(void *)a[1]); /* Address of second row */
    printf("Diff:  %d\n",(a[1] - a[0])); 

    return 0;
}

答案 2 :(得分:1)

您打印的系统a[0]的地址必须为unsigned long int,并且%d说明符在您打印int时接受unsigned long int使用%d说明符,它只打印值的前32位,%d用于签名int,因此值可能为负。

如果要打印a[n][m] m数组的n元素,请使用此语法%p来访问元素所需的值。

如果要打印数组的地址,则需要2说明符。

您的最后一行提供a[0],因为这是a[1]和{{1}}地址之间的差异,虚拟地址由整数表示。