Quote:Original post by Gage64
Decaying the array to a pointer works fine without any warnings, but I don't really understand why it changes anything. Basically I'm trying to understand the behavior "behind the scenes" - I want to understand what causes the access violation.
The unrelying reason is that arrays are not pointers at the implementation level either. The decay-array-to-pointer involves the equivalent of the address-of operator: you don't just reinterpret the bit layout of the array as an adress, you have to actually take the address of the array's first element.
In practice, here's some assembly:
void ptr_frob(int **ptr){ // movq -8(%rbp), %rax // movq (%rax), %rax <--- this line! // movl $10, (%rax) (*ptr)[0] = 10;}void arr_frob(int (*arr)[]){ // movq -8(%rbp), %rax // movl $10, (%rax) (*arr)[0] = 10;}
In short, what gets passed to the second function is the address of the first element of the array, and what is passed to the first function is the address of the address of the first element in the array, so that there is an additional dereference in the first case. When you call the first function with an argument that is compatible with the second function, that second dereference will cause your write to hit whatever the first element of the array (interpreted as an address) pointed at.
In short, at the implementation level, a pointer-to-array is usually just the address of the first element of that array, whereas a pointer-to-pointer is the address of the address of the first element.