I have the following code snippet:
char board[3][3] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'}
};
printf("address of board : %p\n", &board);
printf("address of board[0] : %p\n", &board[0]);
Both printf()
statements all print the same value: 0x0013ff67
As per my knowledge, board (i.e) array name represents the address of the first subarray (i.e) board[0]
and
board[0]
represents the address of first element in the first array (i.e) board[0][0]
Why am I getting the same address in all my printf()
statements? I expect different addresses for both statements.
I am pretty new to this stuff and don't understand this behavior. Kindly enlighten me.
A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element.
An array is treated as a pointer that points to the first element of the array. 2D array is NOT equivalent to a double pointer! 2D array is "equivalent" to a "pointer to row".
A two-dimensional array is similar to a one-dimensional array, but it can be visualised as a grid (or table) with rows and columns. Many games use two dimensional arrays to plot the visual environment of a game.
Here i and j are the size of the two dimensions, i.e i denotes the number of rows while j denotes the number of columns. Example: int A[10][20]; Here we declare a two-dimensional array in C, named A which has 10 rows and 20 columns.
Though it's a 2D array, inside the memory it will be represented as linear array. so when you say, board[0][0] it still points to the first element in that linear array and hence the same memory address.
As per my knowledge, board (i.e) array name represents the address of the first subarray (i.e) board[0]
This is only true if board
is used outside of these contexts
&
operatorsizeof
When any of that applies, expression board
represents the array and keeps having the type of the array (char[3][3]
). Applying the &
operator to it results in getting the address of the array, which of course equals the address of its first element, merely having a different type (char(*)[3][3]
instead of char(*)[3]
). The same that is true about the array board
is true about its first sub array board[0]
.
When you use it outside of those contexts, you get the address of the first element (subarray in your case). That address is not an object but just a value. Value have no address, but objects have. Trying to apply &
on it would fail. For example
// error: trying to apply '&' on something that has no address
&(1 ? board : board)
Note that anything said above applies to C; not necessarily to C++.
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