Are the following same:
extern int a[];
and
extern int *a;
I mean, are they interchangable?
Are the following same:
extern int a[];
and
extern int *a;
I mean, are they interchangable?
No they are not. You'll see the difference when you try something like a++
.
There's plenty of questions about the difference between pointers and arrays, I don't think it's necessary to write more here. Look it up.
They are not the same. The first:
extern int a[];
declares an array of int
. The second
extern int *a;
declares a pointer to int
. As the C FAQ states:
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.
This causes a difference in how the compiler behaves:
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.
You'll have unexpected behavior if you use extern int *a
if a
is actually an array. Given the expression a[3]
, the compiler will treat the first element of a
as an address and try to get the element three places past that address. If you're lucky, the program will crash; if you're not, some data will be corrupted.
extern int a[];
is an array object
extern int *a;
is a pointer that could be pointed to an array of int
See the above links for more information concerning difference between pointer and array object
*(a++) is giving error but not *(a+1)?? where a is array name?
When you see extern int a[]
it tells you that somewhere (may be in other file) is declared an array of integers, while extern int * a
tells you that you have pointer to an integer declared somewhere else and you wish to use it here. There are more differences but that would be another topic.