Here I have an array of 10. How can I make this into a 2D array of say 2 by 5.
double arr1D[10] = {1,2,3,4,5,6,7,8,9,10};
What I want the 2D array to be like:
double arr2D[2][5] = {1,2,3,4,5},{6,7,8,9,10};
Also how would I do it if I had a pointer to an array. So kinda like this:
double arr1D[10];
double*ptr;
ptr = arr1D;
Lets take a closer look at how your arr1D
would look like in memory:
+---+---+---+---+---+---+---+---+---+----+ | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | +---+---+---+---+---+---+---+---+---+----+
It's a simple and contiguous chunk of memory.
Now how would that arr2D
look like in memory? Actually just the same!
So the simplest way is just to use eg std::copy_n
to copy from one array to the other:
double arr1D[10] = {1,2,3,4,5,6,7,8,9,10};
double arr2D[2][5];
std::copy_n(&arr1D[0], 10, &arr2D[0][0]);
For the last code snippet, you don't have a "2D array". Instead the pointer variable ptr
will point to the first element of arr1D
. You can then use ptr
almost as you use arr1D
(the biggest difference is that sizeof arr1D != sizeof ptr
).
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.