Sign in to follow this  
ForeverNoobie

Pointer Arithmetic

Recommended Posts

Try this resource:

http://www.eskimo.com/~scs/cclass/notes/sx10b.html

Or this one:

http://www.eskimo.com/~scs/cclass/notes/sx10b.html

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
Quote:
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this