When first learning C pointers there is one thing I wish had been better explained; operator precedence vs order of operations.
1 2 3 4 5 6 |
int myarray[4]= {1,2,3,0}; int *p = myarray; int out = 0; while (out = *p++) { printf("%d ", out); } |
The above example prints out 1 2 3. Code like *p++ is a common sight in C so it is important to know what it does. The int pointer p starts out pointing to the first address of myarray, &myarray[0]. On each pass through the loop the p pointer address is incremented, moves up one index in the array, but the previous p unincremented address (index) is dereferenced and assigned to the out variable. This happens until it hits the fourth element in the array, 0 at which point the while loop stops. But what does *p++ do? And how does it move from one element in the array to the next. Read more →