Docsity

Pointers Part 5-Computer Fundamentals-Lecture Slides, Slides of Computer Fundamentals

Partial preview of the text

Download Pointers Part 5-Computer Fundamentals-Lecture Slides and more Slides Computer Fundamentals in PDF only on Docsity!

Pointer Arithmetic

yptr = &x ;

yptr ++ ;

a[0] a[1] a[2] a[3] a[4]

*ptr

*(ptr+2) (^) *(ptr+4)

Printing an array

for (int i=0;i<len;i++) printf( "[ %d ] = %d\n" , i , a[i] );

Pointer Comparison

if ( *y1 > *y2 )

if ( *y1 >= *y2 )

if ( *y1 == *y2 )

Passing arrays

void PrintArray(int pnArray, int nLength) { for (int i=0; i < nLength; i++) cout << pnArray[i] << “ “; //pnArray++ }

int main() { int anArray[6] = { 6, 5, 4, 3, 2, 1 }; PrintArray(anArray, 6); }

//Prints 6 5 4 3 2 1

Pointers and 2D arrays

Accessing 2D arrays using a pointer.
  • Element [0][0]
(ptr+0+(02))
  • Element [0][1]
(ptr+1+(02))
  • Element [1][0]
(ptr+0+(12))
  • Element [1][1]
(ptr+1+(12))
Generic way:
Element [i][j]
(ptr+j+(ic))
i=row index
j=column index
c= total columns
r=total rows

v[0][0] v[0][1] V[1][0] V[1][1]

v[0][0] v[0][0] v[0][0] v[0][0]

Logical layout

Actual layout

ptr

#include <stdio.h> int main() { *int r=2,c=4; int a1[2][4]={{1,2,3,4},{5,6,7,8}}; int ptr=a1,i,j; for (i=0;i<r;i++) for(j=0;j<c;j++) { printf( "a1[ %d ][ %d ] = %d\n",i ,j, (ptr+j+(ic)) ); } return 0; }

Pointers and 2D arrays