Convert array to two-dimensional array by pointer

Is it possible to convert a one-dimensional array to a two-dimensional array?

First of all, it will be very simple, just set the pointer of the 2D array to the beginning of the 1D array as follows:

int foo[] = {1,2,3,4,5,6}; int bla[2][3] = foo; 

because I can easily create a two-dimensional array as follows:

 int bla[2][3] = {1,2,3,4,5,6}; 

so now the question is, is there a way to convert it through a pointer?

+4
source share
5 answers

You cannot initialize int bla[2][3] with int* (which foo becomes in this context).

You can achieve this effect by declaring a pointer to int arrays,

 int (*bla)[3] = (int (*)[3])&foo[0]; 

but make sure the sizes actually match or chaos happens.

+8
source

I know that you pointed pointers ... but it looks like you're just trying to get data from an array stored in a 2D array. So, how about just memcpy() content from a 1-dimensional array to a 2-dimensional array?

 int i, j; int foo[] = {1, 2, 3, 4, 5, 6}; int bla[2][3]; memcpy(bla, foo, 6 * sizeof(int)); for(i=0; i<2; i++) for(j=0; j<3; j++) printf("bla[%d][%d] = %d\n",i,j,bla[i][j]); 

gives:

 bla[0][0] = 1 bla[0][1] = 2 bla[0][2] = 3 bla[1][0] = 4 bla[1][1] = 5 bla[1][2] = 6 

What do you want, right?

+4
source

Yes, if you can use an array of pointers:

  int foo[] = {1,2,3,4,5,6}; int *bla[2]={foo, foo+3}; 
+1
source

You can use union to alias one array to another:

 #include <stdio.h> union { int foo[6]; int bla[2][3]; } u = { { 1, 2, 3, 4, 5, 6 } }; int main(void) { int i, j; for (i = 0; i < 6; i++) printf("u.foo[%d]=%d ", i, u.foo[i]); printf("\n"); for (j = 0; j < 2; j++) { for (i = 0; i < 3; i++) printf("u.bla[%d][%d]=%d ", j, i, u.bla[j][i]); printf("\n"); } return 0; } 

Output ( ideone ):

 u.foo[0]=1 u.foo[1]=2 u.foo[2]=3 u.foo[3]=4 u.foo[4]=5 u.foo[5]=6 u.bla[0][0]=1 u.bla[0][1]=2 u.bla[0][2]=3 u.bla[1][0]=4 u.bla[1][1]=5 u.bla[1][2]=6 
+1
source
 int (*blah)[3] = (int (*)[3]) foo; // cast is required for (i = 0; i < 2; i++) for (j = 0; j < 3; j++) printf("blah[%d][%d] = %d\n", i, j, blah[i][j]); 

Note that this does not convert foo from 1D to a 2D array; it just allows you to access the contents of foo as if it were a 2D array.

So why does it work?

First of all, remember that the substring expression a[i] interpreted as *(a + i) ; we find the address of the ith element after a and play the result. So, blah[i] equivalent to *(blah + i) ; we find the address i'th of the 3-element int array after blah and play the result, so the type blah[i] is int [3] .

+1
source

Source: https://habr.com/ru/post/1437403/


All Articles