Array Operator Equivalence

# Array Operator Equivalence - 2D Array 2nd Implementation...

This preview shows pages 1–6. Sign up to view the full content.

Array Operator Equivalence We have the following equivalences: int a[20]; a[i] - is equivalent to *(a+i) - is equivalent to You may substitute array indexing a[i] by *((int*)((char*)&a[0]+i*sizeof(int))) and it will work! C was designed to be machine independent

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2D Array. 1st Implementation 1st approach Normal 2D array. int a[4][3]; a[0] [0]:100: a[0][1]:104: a[0] [2]:108: a[1][0]:112: a[1][1]:116: a[1][2]:120: a[2] [0]:124: a[2][1]:128: a[2] [2]:132: a[3][0]:136: a[3][1]:140: a[3][2]:144: a: a[i][j] == *(int*) ((char*)a + i*3*sizeof(int) + j*sizeof(int))
2D Array 2nd Implementation 2nd approach Array of pointers to rows int*(a[4]); for(int i=0; i<4; i++){ a[i]=(int*)malloc(sizeof(int)*3); assert(a[i]!=NULL);

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: } 2D Array 2nd Implementation • 2nd approach Array of pointers to rows (cont) a[0]:100: a[1]:104: a[2]:108: a[3]:112: a[1][0] a[0][0] a[3][1] a[2][0] a[3][0] a[2][1] a[0][1] a[1][1] a[3][2] a[2][2] a[0][2] a[1][2] int*(a[4]); a[3][2]=5 a: 2D Array 3rd Implementation • 3rd approach. a is a pointer to an array of pointers to rows. int **a; a=(int**)malloc(4*sizeof(int*)); assert( a!= NULL) for(int i=0; i<4; i++) { a[i]=(int*)malloc(3*sizeof(int)); assert(a[i] != NULL) } 2D Array 3rd Implementation • a is a pointer to an array of pointers to rows. (cont.) a[0]:100: a[1]:104: a[2]:108: a[3]:112: a[1][0] a[0][0] a[3][1] a[2][0] a[3][0] a[2][1] a[0][1] a[1][1] a[3][2] a[2][2] a[0][2] a[1][2] int **a; a[3] [2]=5 a:...
View Full Document

## This note was uploaded on 01/30/2012 for the course CS 252 taught by Professor Gustavorodriguez during the Fall '11 term at Purdue.

### Page1 / 6

Array Operator Equivalence - 2D Array 2nd Implementation...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online