C - 数组和指针

Pro*_*mer -4 c

我正在尝试编译并运行我的下面的程序.

#include <stdio.h>

main()
{
        int (*x)[7];
        int a[7] = {2,3,4,5,6,7,8,9};
        int i = 0;
        x=a;
        for (i=0; i < 7 ; i++)
                printf("%d\n", x[i]);
}
Run Code Online (Sandbox Code Playgroud)

根据代码,我创建了一个指针x指向一个内存位置,该内存位置有七个连续的内存块来存储整数.

但我不断收到编译器警告和错误输出:

desktop:~$ gcc a1.c 
a1.c: In function ‘main’:
a1.c:6:2: warning: excess elements in array initializer [enabled by default]
a1.c:6:2: warning: (near initialization for ‘a’) [enabled by default]
a1.c:8:3: warning: assignment from incompatible pointer type [enabled by default]
a1.c:10:3: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]

desktop:~$ ./a.out 
-1081431716
-1081431688
-1081431660
-1081431632
-1081431604
-1081431576
-1081431548
Run Code Online (Sandbox Code Playgroud)

为什么会出现这些警告和输出?

Vla*_*cow 5

改变这个陈述

    int (*x)[7];
Run Code Online (Sandbox Code Playgroud)

    int *x;
Run Code Online (Sandbox Code Playgroud)

int (*x)[7];是指向具有类型的对象的指针的声明int[7].因此,例如表达式x [1]将具有7 * sizeof( int )大于存储在x中的地址的地址.这不是你想要的.

数组a的初始化程序(= 8)也比其维数(= 7)多

考虑到函数main应具有返回类型int.

正确的程序看起来像

#include <stdio.h>

int main( void )
{
        const int N = 8; 
        int *x;
        int a[N] = { 2, 3, 4, 5, 6, 7, 8, 9 };
        int i;

        x = a;
        for ( i = 0; i < N ; i++)
                printf( "%d\n", x[i] );
}
Run Code Online (Sandbox Code Playgroud)