Changing Through a Pointer
*p isn't only for reading. It stands for the variable itself, so you can also assign to it. *p = 20; stores 20 in the box p points to:
#include <stdio.h>
int main(void) {
int age = 15;
int *p = &age;
*p = 20;
printf("age: %d\n", age);
*p += 1;
printf("age: %d\n", age);
return 0;
}This prints:
age: 20
age: 21The program never writes age = ..., and yet age changed. age and *p are two ways to reach the same box. So *p works everywhere age would: *p = *p * 2;, *p -= 3;.
Careful with ++: write *p += 1; or (*p)++;. Without the parentheses, *p++; adds 1 to the pointer itself (it moves it to the next box) and doesn't change age, and no error tells you.
Without the star, you change the pointer itself, that is, where it points. That's useful too. In this game, the pointer player always points to the score of the player whose turn it is:
int anna = 0;
int peter = 0;
int *player = &anna;
*player += 5;
player = &peter;
*player += 3;
printf("Anna: %d, Peter: %d\n", anna, peter);This prints:
Anna: 5, Peter: 3player = &peter; without a star points player to another variable. *player += 3; with a star changes the variable it points to now, peter.
So remember: *p = ... with a star changes the value in the box. p = ... without a star changes where p points, and it needs an address. When you forget the star in *p = 20;, the line p = 20; ends with the error incompatible integer to pointer conversion assigning to 'int *' from 'int': you are trying to put the number 20 into the pointer itself.
Instructions
Below the variables (above printf), create a pointer p that points to lives. Below it, set the lives to 5 through the pointer: *p = 5;. Don't write lives = 5;. The program prints Lives: 5, shields: 1.
Below it (still above printf), add 2 more lives, again through the pointer. The program prints Lives: 7, shields: 1.
Now the pointer should point to the shields. At the end of the program (before return 0;), point p to the variable shields.
Below it, add 1 shield through the pointer and print the line with the lives and shields again, the same way. The program prints Lives: 7, shields: 1 and then Lives: 7, shields: 2.
Start programming for free
4/11