Pointer Introduction
What is a Pointer?
Pointers are very important in C programming because they allow you to easily work with memory locations.
They are fundamental to arrays, strings, and other data structures and algorithms.
A pointer is a variable that contains the address of another variable. In other words, it "points" to the location assigned to a variable and can indirectly access the variable.
Pointers are declared using the * symbol and take the form:
pointer_type *identifier
pointer_type is the type of data the pointer will be pointing to. The actual pointer data type is a hexadecimal number, but when declaring a pointer, you must indicate what type of data it will be pointing to.
Asterisk * declares a pointer and should appear next to the identifier used for the pointer variable.
The following program demonstrates variables, pointers, and addresses:
#include <stdio.h>
int main() {
int j = 63;
int *p = NULL;
p = &j;
printf("The address of j is %x\n", &j);
printf("p contains address %x\n", p);
printf("The value of j is %d\n", j);
printf("p is pointing to the value %d\n", *p);
}
There are several things to notice about this program:
• Pointers should be initialized to NULL until they are assigned a valid location.
• Pointers can be assigned the address of a variable using the ampersand & sign.
• To see what a pointer is pointing to, use the * again, as in *p. In this case the * is called the indirection or dereference operator. The process is called dereferencing.
The program output is similar to:
The address of j is ff3652cc
p contains address ff3652cc
The value of j is 63
p is pointing to the value 63
Some algorithms use a pointer to a pointer. This type of variable declaration uses **, and can be assigned the address of another pointer, as in:
int x = 12;
int *p = NULL
int **ptr = NULL;
p = &x;
ptr = &p;
Pointers in Expressions
Pointers can be used in expressions just as any variable. Arithmetic operators can be applied to whatever the pointer is pointing to.
For example:
#include <stdio.h>
int main() {
int x = 5;
int y;
int *p = NULL;
p = &x;
y = *p + 2; /* y is assigned 7 */
y += *p; /* y is assigned 12 */
*p = y; /* x is assigned 12 */
(*p)++; /* x is incremented to 13 */
printf("p is pointing to the value %d\n", *p);
}
Comments
Post a Comment