C输出因代码不同而不同

时间:2017-08-21 10:22:10

标签: c++ c gcc

#include <stdio.h>
#include <stdlib.h>

int main() {

    int* a[10];
    int* p = a;
    int i = 0;
    for (p = &a[0], i = 0; p < &a[10]; p++, i++)
    {
        *p = i;
    }
    for (int i = 0; i < 10; i++)
    {
        printf("%d\n", a[i]);
    }
}

使用eclipse在GCC上输出:

0
2
4
6
8
10
12
14
16
18

使用visual studio输出:

0
1
2
3
4
5
6
7
8
9
为什么?

2 个答案:

答案 0 :(得分:5)

% gcc error.c -Wall -Wextra
error.c: In function ‘main’:
error.c:7:14: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
     int* p = a;
              ^
error.c:9:12: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
     for (p = &a[0], i = 0; p < &a[10]; p++, i++)
            ^
error.c:9:30: warning: comparison of distinct pointer types lacks a cast
     for (p = &a[0], i = 0; p < &a[10]; p++, i++)
                              ^
error.c:15:18: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
         printf("%d\n", a[i]);
                  ^

提示:

int a[10]; // notice the lack of star here.

答案 1 :(得分:1)

a被声明为一个包含10个指向int的数组。 a中的int* p = a;会衰减到int **,但p的类型为int *。编译器将发出有关不兼容指针赋值的警告。您需要更改声明

int* a[10];  

int a[10];

该程序调用未定义的行为,因此可能会发生奇怪的事情。

相关问题