#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]);
}
}
Run Code Online (Sandbox Code Playgroud)
使用eclipse在GCC上的输出:
0
2
4
6
8
10
12
14
16
18
Run Code Online (Sandbox Code Playgroud)
使用visual studio输出:
0
1
2
3
4
5
6
7
8
9
Run Code Online (Sandbox Code Playgroud)
为什么?
% 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]);
^
Run Code Online (Sandbox Code Playgroud)
暗示:
int a[10]; // notice the lack of star here.
Run Code Online (Sandbox Code Playgroud)