Charles
Charles

Reputation: 11479

Getting one-dimensional arrays from a two-dimensional array

I have an array like

int outer[4][3] = {
    { 1, 2, 3 },
    { 2, 3, 5 },
    { 1, 4, 9 },
    { 10, 20, 30 }
};

and I would like to get a pointer/array for the n-th one-dimensional array inside outer, something like

void foo () {
    printf("%d %d %d\n", outer[1][0], outer[1][1], outer[1][2]);
    int inner[3] = outer[1]; /* Is there some way to do this assignment? */
    printf("%d %d %d\n", inner[0], inner[1], inner[2]);
    /* so that this line gives the same output as the first */
}

Of course this is possible with pointer math, but I feel like there is some syntax for this that I've forgotten.

Upvotes: 6

Views: 68

Answers (1)

haccks
haccks

Reputation: 105992

For pointer to array, declare inner as a pointer to an array of 3 int

int (*inner)[3] = &outer[1]; 


If you want a pointer to first element of array outer[1] then

int *inner = outer[1];  

will do the job. You can also do

int *inner = &outer[1][0];

Upvotes: 6

Related Questions