-
Step 1
Understand that memory pointer variables always point to data of a particular type. For instance, a pointer to an int is different from a pointer to a char. However, C will not stop you from freely mixing them up. Do so only if you're sure you know what you're doing.
-
Step 2
Create a memory pointer variable by using the syntax you'd use to create a variable of the desired type, but with an asterisk (*) before the variable name, like this:
int *x;
-
Step 3
Consider NULL. Pointers can always be NULL (0), and this typically is used to refer to a pointer that has not yet been set to point anywhere.
-
Step 1
Get to know Referencing. Referencing refers to the process of finding the pointer to an existing variable. In C, the referencing operator is the ampersand (&). For instance:
int color = 5;
int *pointer_to_color;
pointer_to_color = &color; -
Step 2
Utilize Dereferencing. Dereferencing is the process of following a pointer to its value, the opposite of referencing. In C the asterisk (*) is used for dereferencing, as follows:
printf("Color is %d\n", *pointer_to_color); /* prints 5 */ -
Step 1
Pass in a pointer to the variable when you need a function to be able to change a variable, instead of passing the variable's value. This lets the function use dereferencing to change the value:
void convert_color_to_RGB(int color, int *red, int *green, int *blue) {
*red = redpart(color);
*green = greenpart(color);
*blue = bluepart(color);
}
convert_color_to_RGB(15, &myred, &mygreen, &myblue); -
Step 2
Work around C's limits. Whenever you want to pass an array or structure into a function, you must pass a pointer instead, because C only permits single data types to be passed to functions:
int subtotal(int *scores, int howmany) {
int total = 0, i;
for (i = 0; i < howmany; i++) total += scores[i];
return total;
} -
Step 3
Create a loop. Since strings are actually arrays of characters, you can create a pointer to a character to loop through a string:
void replace_character(char *s, char from, char to) {
char *cp;
for (cp = s; cp && *cp; cp++) if (*cp == from) *cp = to;
} -
Step 4
Understand the way C views arrays. Arrays are handled by C as pointers, using pointer arithmetic. C will automatically multiply what you add to a pointer by the size of elements it points to. That means
scores[5] = 17;
is exactly the same as*(scores + 5) = 17;
. You can use pointers as a shorthand for array dereferences. For instance,*scores = 17;
always refers to the 0th element of the array.











