1

I have two arrays

int x[]={1,2,3,4};
int y[]={5,6,7};

I like to create two dimensional array. assign x and y. Can I do something like this

int x[]={1,2,3,4};
int y[]={5,6,7};
int *k=x;
int *l=y;
int **m={k,l};
printf("%d\n",m[0][0]);

but at printf when 1 is get accessed throws segFault

What I am doing wrong

1
  • I'm surprised that the compiler swallowed int **m={k,l};. Your code should work if you change that line to int *m[2]={k,l};, making m an array and not a pointer; this could (and should, for robustness) be changed to int *m[]={k,l};. The latter deduces the (still fixed at compile time) array size from the number of items between the braces, so you don't have to change a number if in the future you add another array element. But it is still a true array with two elements and not a pointer like int **m is. Commented May 12, 2021 at 10:52

2 Answers 2

4
int **m={k,l};

is wrong. This is assigning the value of k (int*) to the variable m (int**) and leaving the excess element l in the initializer unused.

You can use an array

int *m[]={k,l};

or a compound literal

int **m=(int*[]){k,l};

instead.

Sign up to request clarification or add additional context in comments.

Comments

1

Arrays are not pointers. Pointers are not arrays. And therefore pointer-to-pointers are not arrays of arrays either.

Arrays may in some circumstances "decay" into pointers to their first element, but that doesn't make them pointers.

Correct code in your case is:

int x[]={1,2,3,4};
int y[]={5,6,7};

int xy[4][3];
memcpy(xy, x, 4*sizeof x);
memcpy(xy, y, 3*sizeof y);

Or alternatively allocate the 2D array dynamically:

int (*xy)[3] = malloc( sizeof(int[4][3]) );

If it makes sense, you could create a pointer-based look-up table using pointers:

int* table [2] = {x, y};

But this will likely have slower access time than a 2D array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.