Analogy: Incrementing and Decrementing Pointer What if, we use increment or decrement operator in pointers, like we do with integer data type. Analogy with Integer #include < stdio.h > int main(){ int a = 1; int b; b = a++; printf ("a: %d b: %d", a, b); return 0; } Output a: 2 b: 1
Implementation: Incrementing and Decrementing Pointer So if we follow similar syntax as followed in last slide for integers, as shown in code below. #include < stdio.h > int main(){ int *a = 1; a*++; printf ("%d", *a); return 0; } So, will it increment the value of integer stored in the address of the pointer? Not really.
Theory: Incrementing and Decrementing Pointer If you use increment or decrement operator on pointer, C will increment or decrement pointer to respective memory address. Hence, the code in previous slide will not increment the value, instead will increment the pointer address. Address 100 200 300 Value 1 2 3
Sounds Great?
Example of Increment and Decrement in Pointers Let's dive into the syntactically correct and working example of the Pointer Arithmetic. Code #include < stdio.h > int main(){ int a = 1; int *b = &a; printf ("Value: %d\n", *b); *b++; printf ("Value: %d", *b); return 0; } Output Value: 1 Value: 1662454488
But, Why a random number? After incrementing we can notice a random number because, after incrementation, pointer has changed the address to another memory location, so, the new target location may already have a value stored by any other program running on the computer, or may have some garbage value. Address 100 200 300 Value 1454545 1 54654646
Using pointers to iterate through arrays
Using pointers to iterate through arrays Now, we know that increment and decrement operators, increment to next pointer address and decrement to previous pointer address respectively. Using this analogy we can implement it in array. So, in array, we can use increment operator on pointer to jump to next index of the array and decrement operator to jump to previous index in array.
Aim Let's say we have an array as below. int a[2] = {1,2,3}; We have to print all elements of array using pointers.
Implementation We can use the code below. #include < stdio.h > int main(){ int a[2] = {1,2,3}; int *b = &a[0]; for (int i =1;i<10;i++){ printf ("%d. %d\n", i , *b); *b++; } return 0; } So we are running loop for 9 iterations, to show you with some garbage values.
How to pass address to function You can pass address of a variable using address operator. And get the value by creating pointer in parameters in function. Refer to the code below #include < stdio.h > void dothis (int *a){ printf ("%d", *a); } int main(){ int b = 1; dothis (&b); return 0; }