以下は同じです:
extern int a[];
と
extern int *a;
つまり、それらは交換可能ですか?
いいえそうではありません。のようなものを試してみると、違いがわかりますa++
。
ポインターと配列の違いについてはたくさんの質問がありますが、ここで詳しく書く必要はないと思います。調べる。
それらは同じではありません。最初:
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
アドレスとして扱い、そのアドレスの 3 つ先の要素を取得しようとします。運が良ければ、プログラムはクラッシュします。そうしないと、一部のデータが破損します。
extern int a[];
配列オブジェクトです
extern int *a;
intの配列を指すことができるポインタです
ポインターと配列オブジェクトの違いに関する詳細については、上記のリンクを参照してください。