Jump to content
  • Advertisement
Sign in to follow this  

Pointer Arithmetic

This topic is 4583 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there a way to use pointer arithmetic with 2d arrays? If so can someone give me an example? Sory if this is a dumb question, my book doesnt cover it.

Share this post

Link to post
Share on other sites
Try this resource:


Or this one:


Share this post

Link to post
Share on other sites
yes, you can do pointer arithmetic with 2d arrays, 3d, whatever dimention you want to really, by treating it as a linear array, and multiplying the value of the row you want, by the width of the array. 2D arrays are just 1D arrays that are arranged differently.. here is an example

#include <iostream.h>

int main()
int twoD[10][10];//defined column, row
int *oneD;
oneD = (int*) twoD;
twoD[0][0] = 1;
twoD[1][0] = 2;
twoD[0][1] = 3;
twoD[1][1] = 4;
int* addr = (int*)(twoD);
cout << *addr << " " << oneD[0] << endl;// regular reference, row 0, column 0;
cout << *(addr + 1) << " " << oneD[1] << endl;// add 1, so first column, row 0, column 1
cout << *(addr + 10) << " " << oneD[1 * 10]<< endl; // add the the column width, to make a row increase , so row 1, column 0
cout << *(addr + 11) << " " << oneD[(1 * 10) + 1] << endl; // add width + 1, so row 1, column 1
//should yeild 1 2 3 4
return 1;

let Y be the row you want, and X be the column you want, and P be the domain upper bound + 1, overwhich there is a valid X value ( for example, variable[10][10], a valid number is 0 through 9, so P would be 10, being the upper bound of 9, plus 1) Then the one dimentional representation is array[(Y * P) + x]. so the pointer arith representation is *(address + ((Y*P)+X))

The same logic can be extended to any dimention, by multiplying by the pitch of that dimention.

This applies to C/C++, not sure about java, VB, others

Share this post

Link to post
Share on other sites
Guest Anonymous Poster
Original post by ForeverNoobie
Ok I get it. Thats alot easier than I expected.

If you are going to use them excessively/incessantly, try to get your arrays to be powers of 2 so that you can use shifts instead of multiplies (or let the compiler do it if its smart enough). Of course if the step size (sizeof array element structures) arent power of 2 (like the basic types 1 2 4 8 sizes) it will be doing multiplies anyway....

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!