以下是否相同:
extern int a[];
和
extern int *a;
我的意思是,它们可以互换吗?
不,他们不是。当您尝试类似a++
.
关于指针和数组的区别有很多疑问,我觉得这里没必要多写。查一下。
它们是不相同的。首先:
extern int a[];
声明一个数组int
。第二
extern int *a;
声明一个指向int
. 正如C 常见问题解答所述:
The array declaration "char a[6]" requests that space for six characters be set aside,
to be known by the name "a". That is, there is a location named "a" at which six
characters can sit. The pointer declaration "char *p", on the other hand, requests a
place which holds a pointer, to be known by the name "p". This pointer can point
almost anywhere: to any char, or to any contiguous array of chars, or nowhere.
这会导致编译器的行为方式有所不同:
It is useful to realize that a reference like "x[3]" generates different code
depending on whether "x" is an array or a pointer. Given the declarations above, when
the compiler sees the expression "a[3]", it emits code to start at the location "a",
move three past it, and fetch the character there. When it sees the expression "p[3]",
it emits code to start at the location "p", fetch the pointer value there, add three
to the pointer, and finally fetch the character pointed to. In other words, a[3] is
three places past (the start of) the object named a, while p[3] is three places
past the object pointed to by p.
如果你使用extern int *a
ifa
实际上是一个数组,你会有意想不到的行为。给定表达式a[3]
,编译器会将 的第一个元素a
视为地址,并尝试获取该地址后三个位置的元素。如果幸运的话,程序会崩溃;如果你不是,一些数据将被破坏。
extern int a[];
是一个数组对象
extern int *a;
是一个可以指向 int 数组的指针
有关指针和数组对象之间差异的更多信息,请参阅上面的链接
当你看到extern int a[]
它告诉你某处(可能在其他文件中)声明了一个整数数组,同时extern int * a
告诉你你有一个指向在其他地方声明的整数的指针,你希望在这里使用它。还有更多差异,但这将是另一个话题。