Lets say I have a populated integer 2D array represented by a double pointer. I try to access the elements like this (this is just a piece of the code):
int **array;
while (i<arraysize) {
printf("array[%d] = %d", i, array+i);
}
I know in memory 2D arrays are bascially stored as 1D arrays. How can I print all of the elements without using a nested for loop?
Yes, a C 2D array is an array of arrays. C arrays consist of elements laid out contiguously in memory, so the (array) members of a 2D array are contiguous in memory, and their own elements are contiguous within them, so that the overall layout is congruent with the layout of a 1D array.
But what you present is not a 2D array, nor a pointer to one, nor in any way compatible with one. Yours is a pointer to pointer to int
. Such a pointer might point to the first element of an array of int *
, but it only points anywhere into a 2D array if the programmer has somewhere performed a conversion between incompatible pointer types, directly or indirectly. A direct conversion ought to raise a warning, but an indirect one, say through a void *
intermediate, might compile cleanly even with warnings turned up to 11.
The declaration of a C 2D array has this form:
int array_2d[4][2];
Such an array decays to a pointer of this type under most circumstances:
int (*array_2d_pointer)[2];
In direct answer to your question, then,
How can I print all of the elements without using a nested for loop?
You can't. Your data are not structured for that.
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.