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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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
intobject. Since your array is actually a sequence ofintobjects, and not pointers tointobjects, you’re actually trying to dereference to some memory location that isn’t pointing to anywhere valid (i.e., the first slot inarrayis a numerical integer value like0which would be like dereferencing a NULL). So that is why you’re segfaulting. Note that if you had done something like this:That still works, since
arrayis 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.