#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
为什么?
答案 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];
该程序调用未定义的行为,因此可能会发生奇怪的事情。