File 1.c
int a[10];
File main.c:
extern int *a; int main() { printf("%d\n", a[0]); return 0; }
Gives me a segfault! What's going wrong?
Arrays decompose, or are implicitly converted to pointers when passed to a function as an argument, or when converted to an r-value on the right-hand-side of the assignment operator. So something like:
int array[10]; int* a = array; //implicit conversion to pointer to type int void function(int* a); function(array); //implicit conversion to pointer to type int
works just fine. But that does not mean that arrays themselves are pointers. So if you treat an array like a pointer as you've done, you're actually treating the array type as-if it was a pointer that held the address to an int
object. Since your array is actually a sequence of int
objects, and not pointers to int
objects, you're actually trying to dereference to some memory location that isn't pointing to anywhere valid (i.e., the first slot in array
is a numerical integer value like 0
which would be like dereferencing a NULL). So that is why you're segfaulting. Note that if you had done something like this:
int array[] = { 1, 2, 3, 4, 5}; int b = *array;
That still works, since array
is again implicitly converted to a pointer to the memory block that is holding a sequence of integer values and is then dereferenced to get the value in the first sequence. But in your case, by declaring your array to the current code module as an externally defined pointer, and not an array, it will skip over the implicit conversion to a pointer that is normally done, and just use the array object as-if it were a pointer to an object itself, not an array of objects.
Well explained in the C FAQ. And there is a followup. The picture in the second link is worth a million bucks.
char a[] = "hello"; char *p = "world";
Short answer: use extern int a[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With