Tor Klingberg
Tor Klingberg

Reputation: 5098

Can I access a pointer as a 2D array in C?

Lets' say I have a pointer to int:

int *p = somefunc();

I know it points to 25 ints, logically arranged in a 5x5 grid. I can access an element with this:

p[y*5+x]

or this:

*(p+y*5+x)

Is there a way access it as a 2D array?

a[y][x]

Upvotes: 2

Views: 64

Answers (2)

Senua
Senua

Reputation: 586

I'd do a simple function to do it :

int at(int * p, int x, int y)
{
    return p[y*5+x]
}

You can add another parameter for less specific width of table (i.e. other that 5), but that's how I usually do it.

Upvotes: 1

melpomene
melpomene

Reputation: 85887

Yes:

int (*a)[5] = (int (*)[5])p;

Upvotes: 8

Related Questions