Jump to content


how to create a pointer to 2D array in C


5 replies to this topic

#1 hunguptodry

    New Member

  • Members
  • PipPip
  • 31 posts

Posted 23 April 2010 - 03:32 AM

Say, I have several 2D arrays, all with the same dimensions

int mapa[512][512];
int mapb[512][512];
int mapc[512][512];

I want to create a pointer (or some kind of alias) mapX,
and use it like so

//some magic to set mapX to point to mapa here
mapX[5][5] = 1; // equiv to mapa[5][5] = 1
.
.
.
//some magic to set mapX to point to mapb here
mapX[6][7] = 1; // equiv to mapb[6][7] = 1
.
.
.
//some magic to set mapX to point to mapc here
mapX[1][2] = 1; // equiv to mapc[1][2] = 1

#2 Sol_HSA

    Senior Member

  • Members
  • PipPipPipPip
  • 510 posts
  • LocationNowhere whenever

Posted 23 April 2010 - 04:36 AM

Step one: ditch the 2d arrays. You can do the (y*width+x) calculation yourself easily enough. This also simplifies things a lot.

If you're not able or willing to do so, however, realize that 2d arrays are nothing magical, and the compiler actually has a 1d array and is doing the above calculation for you every time you're using a 2d array.

To actually answer your question, you can make a typedef of the 2d array and then use that as the pointer type.
typedef int maptype[512][512];

http://iki.fi/sol - my schtuphh

#3 hunguptodry

    New Member

  • Members
  • PipPip
  • 31 posts

Posted 23 April 2010 - 05:23 AM

too much code to change, so sticking with the 2D arrays.
the typedef worked great. thanks.

#4 Almos

    Member

  • Members
  • PipPip
  • 99 posts

Posted 26 April 2010 - 07:57 AM

One suggestion, if I may - perhaps not too smart, but still...


#define X_DIMENSION 512

#define Y_DIMENSION 512


typedef int maptype[X_DIMENSION][Y_DIMENSION];


I want to make a game as good as Elder Scrolls oblivion with no programming, just point&click. If it's not possible, I want a team of programmers I'd be able to order around. After all, I'm a n00b.

#5 Reedbeta

    DevMaster Staff

  • Administrators
  • 5307 posts
  • LocationSanta Clara, CA

Posted 26 April 2010 - 04:15 PM

Almos, it would be better to do something like:

static const int xDim = 512;
static const int yDim = 512;

typedef int maptype[xDim][yDim];

reedbeta.com - developer blog, OpenGL demos, and other projects

#6 .oisyn

    DevMaster Staff

  • Moderators
  • 1842 posts

Posted 26 April 2010 - 08:55 PM

For completeness sake, without the typedef it would've been:
int (*mapX)[512] = mapa;
mapX[1][2] = 3;
The idea is that, just like with an array of ints where you'd point to the first element in the array, now you have to point to the first element in an array of [array of int]. And each such element is an array of 512 ints, in other words, int[512].
C++ addict
-
Currently working on: the 3D engine for Tomb Raider.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users