2

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]

2 Answers 2

8

Yes:

int (*a)[5] = (int (*)[5])p;
Sign up to request clarification or add additional context in comments.

2 Comments

Is it not possible without explicit casting?
@TorKlingberg As far as I know, no.
1

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.

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.