user1754940
user1754940

Reputation: 197

The following code resulting in either garbage or access violation error why is it so...?

file1.c

int a[3]={1,39,7}; /* definition */

file2.c

extern int a[]; /* declaration */
b = a[2]; /* correct usage in file2.c */

file3.c

extern int *a; /* another declaration */
c = a[1]; /* a[1] is *(a+1), fails! */

The usage in file2 obtains the 3rd element (7) of a, but the usage in file2 interprets 39 as an address (assuming 32 bit integers and addresses), resulting in either garbage or access violation error why is it so...?

Upvotes: 2

Views: 79

Answers (1)

Daniel Rose
Daniel Rose

Reputation: 17648

Look at this answer in the C FAQ. int *a and int a[] are not the same!

EDIT: Modified from the answer there:

In one source file you defined an array of ints and in the other you declared a pointer to ints. [...] The type pointer-to-type-T is not the same as array-of-type-T.

EDIT #2: To see what happens, look at this answer. The relevant parts, modified to fit your sample:

a2 [in file2.c] is two places past (the start of) the object named a, while a1 [in file3.c] is one place past the object pointed to by a.

So in file3.c it believes a to be a pointer, which is dereferenced. Since it actually is the array itself, this is dereferenced to somewhere else, which results in the access violation.

Upvotes: 7

Related Questions