CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Combining pointer arithmetic and dereferencing

With great care (because it's confusing), we can also combine pointer arithmetic with dereferencing:


#define N    5 

int totals[N];
int *p = totals ;

    for(int i=0 ; i<N ; ++i) {
        *p++ = 0; // set what p points to to zero, and then   
                  // advance p to point to the "next" integer   
    }

    for(int i=0 ; i<N ; ++i) {
	printf("value of totals[%i] is:  %i\n", i, totals[i] );   
    }

In English, we read this as:

"set the contents of the location that the pointer p currently points to the value zero, and then increment the value of pointer p by the size of the variable that it points to" 🤪

Similarly we can employ pointer arithmetic in the control of for  loops. Consider this excellent use of the preprocessor:


int array[N];
int n, *a;

#define FOREACH_ARRAY_ELEMENT  for(n=0, a=array ; n<N ; ++n, ++a) 

    FOREACH_ARRAY_ELEMENT {
        if(*a == 0) {
            .....
        }
    }

 


CITS2002 Systems Programming, Lecture 11, p9, 28th August 2023.