# Pointer Arithmetic

## 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 on other sites
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 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 on other sites
Ok I get it. Thats alot easier than I expected.

##### Share on other sites
Quote:
 Original post by ForeverNoobieOk 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....

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627676
• Total Posts
2978582

• 11
• 12
• 10
• 12
• 22