以下是相同的:
extern int a[];
和
extern int *a;
我的意思是,他们可以互换吗?
答案 0 :(得分:2)
不,他们不是。当你尝试a++
之类的东西时,你会看到差异。
有很多关于指针和数组之间差异的问题,我认为没有必要在这里写更多内容。查一查。
答案 1 :(得分:0)
extern int a[];
是一个数组对象
extern int *a;
是一个可以指向int
数组的指针有关指针和数组对象之间差异的更多信息,请参阅上面的链接
*(a++) is giving error but not *(a+1)?? where a is array name?
答案 2 :(得分:0)
当你看到extern int a[]
它告诉你某个地方(可能在其他文件中)被声明为一个整数数组时,extern int * a
告诉你你有一个指向其他地方声明的整数的指针而你希望在这里使用它。有更多的差异,但这将是另一个主题。
答案 3 :(得分:0)
他们不一样。第一个:
extern int a[];
声明一个int
数组。第二个
extern int *a;
声明指向int
的指针。正如C FAQ所述:
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
a
实际上是数组,则会出现意外行为。给定表达式a[3]
,编译器会将a
的第一个元素视为一个地址,并尝试将该元素放在该地址之后的三个位置。如果你很幸运,程序会崩溃;如果你不是,一些数据将被破坏。