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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…