Does name of a 2D array give its base address in C like in 1D array? And how can i store the base address of a 2d array in a pointer variable?
It decays to a pointer to the first element:
int a[5][7];
decays to
int (*pa)[7] = a;
In practice, the value stored in pa
will be the same as that of a pointer to the first int
element of a
, but the correct way to get a pointer to the first element of a
is to use
int *p_elm = &(a[0][0]);
or equivalently
int *p_elm = &(pa[0][0]);
However, note that a pointer to the first element can't (strictly) be treated as a pointer to the beginning of a N*M
array; see eg http://www.lysator.liu.se/c/c-faq/c-2.html#2-11
是的,您将地址存储为:
int *p = &a[0][0];
A 2D array is essentially a 1D array, where each element itself is an array.
The name of the array is equivalent to &arrayName[0].
Assigning a pointer to this address is same as always, something like:
int myArray[5][5];
int (*arrayptr)[5] = myArray;
This says arrayptr
is a pointer to an array of 5 integers. Since myArray
is an address to the first element, which is an int[5]
, our declaration is fine.
When you dereference this pointer however, you're going to get the first element, which is an array. Therefore you can do something like:
(*arrayptr)[3]; // parens necessary for precedence issues
to access the 3rd element in the array nested inside the first element of the "outer array". It is the equivalent of
myArray[0][3];
What's happening is you're dereferencing arrayptr
which will yield a 1D array (of size 5 in this case).. then you're asking for the 4th element of this 1D array.
Now, if what you're looking for is the top-left "corner" of the matrix, you will want:
int *topleft = &(myArray[0][0]);
Use the address of operator to point to the offset of base.
char base[2][2];
int *basepointer = &base;
I would like to give answer specific to your question.
Whenever you pass name of a 2D Array, that name of array will be decayed into pointer to first element,
In a multi-dimensional array, as multi dimensional array is array of arrays, so first element will be array itself.
So name of 2D array will be decayed to pointer to array, ie pointer to first row having number of elements equal to number of columns in your 2D array.
Remember 2D array is received in a function as pointer to array not pointer to pointer.
int main()
{
int arr[2][3];
display(arr);
............
}
void display( int (*arr)[3])
{
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.