Say I have an int array: int arr[5][5] and assume C language memory management.
I want to access a particular element of the array using only pointer arithmetic and dereferencing.
Suppose I wanted to access the element in: arr[i][j]
I tried printing a few things at first to understand how the addresses worked.
I printed the address of arr, arr+1, and arr+2, and arr+5.
These were the results:
0x7fff58475b80
0x7fff58475b94
0x7fff58475ba8
0x7fff58475be4
I'm wondering why the difference between each of address is 14(in Hexadecimal) or 20 (in decimal).
Also, when you create a 2-D array on the stack, is a pointer to an array of pointers to memory blocks created? This is how I assume we allocate space for the array:
- Allocate a pointer
arron stack. - The
arrpointer holds the address to the starting location of an array of pointers. - That array of pointers contains the starting location of a row in the 2-D array.
Is this correct?
EDIT: Also, assume you wanted to access arr[i][j] through pointer arithmetic. How would this be done? If the array is allocated dynamically, I think you can do *( * (arr+i)+j). I'm not sure how you do this for static allocations? My guess is *(arr + ((row_size * (i))+j)). Is this correct?
arris an array of 5 elements, of typeint[5]each.sizeof(int[5]) == 20is a pointer to an array of pointers to memory blocks created?No. A flat array of "memory blocks" is created, each "block" in turn an array. Perhaps this will make it clearer:int arr[5][5]is the same astypedef int Block[5]; Block arr[5];int arr[5][5];. Arrays and pointers are different.