How to Program C Pointers
The C programming language pointers are variables that contain the address space for another variable. Since pointers "point" to an address space, changing the pointer's value also changes the variable assigned to the pointer. Passed back and forth between functions, pointers allow programmers to control values even when the variable is not global. The C programming language defines pointers using the asterisk prefix.
Instructions
-
-
1
Create your variable. Pointers are assign variable address spaces. Therefore, before you define a pointer, you need a variable. The code below shows you how to define a variable in C:
int theInt = 0;
-
2
Define your pointer. Pointers are easily recognizable in your program, because it has an asterisk prefix. The following code defines a pointer:
int *ptr;
-
-
3
Assign the variable to the pointer. You assign the address space to the pointer, which is accomplished using the ampersand symbol. Each time you see an ampersand prefix in C, think "address of." The following code assigns the address of the integer to the pointer:
ptr = &theInt;
Since "theInt" is defined with a 0 value, the ptr variable contains the value of 0.
-
4
Change the value of the variable. Now that the pointer is assigned to the variable, changing the pointer value changes the actual variable as well, The following code shows you how to change variable values using a pointer:
*ptr = 5;
-
5
Print the results to view the value changes. This helps you learn and view the code execution and how it affects pointers. The following code prints the results to your console:
theInt = 1;
printf("The value of theInt is %d", theInt); //prints out 5
*ptr = 10;
printf("The value of theInt is now %d", theInt); //prints out 10
-
1
References
- Photo Credit Blue Asterisk Accent image by K. Geijer from Fotolia.com