Pointer and Dynamic Array Summary:
· General:
o A pointer variable holds an address.
o A pointer variable that points to a pointer variable holds an address that in turn points to an address.
o A Multi-dimensional array variable is a pointer to a pointer, because each row is referred to by a pointer.
o Print addresses with %p format character.
· Declare a pointer:
o Read backwards: double * p means: p is a pointer to a double
o Not dynamic: point to a variable that was created with a normal <type> <variable name> declaration
§ double x
§ double * p = &x
o Dynamic:
§ Create a pointer with a null value, and then assign a block of memory using malloc in the heap and then store the starting address in your pointer:
· double * p1;
· p1 = (double *) malloc(sizeof(int));
o (note cast of void pointer malloc returns to the type of pointer you want.)
o If malloc returns NULL, no memory was assigned. - You must check
§ When you are done using memory you grabbed with malloc, you must free it.
· free(p1);
§ Set pointer to NULL when it point to nothing: p2 = NULL;
· Use a pointer:
o Use the address: Just the variable name : ptr
o Set pointers to either the value of another pointer (such as an array) or the address of another variable (any type, even a pointer).
o Use the value at the address: deference the pointer : *ptr
o Get the address of another variable: &varname
o Remember that the array variable is a pointer, and the cells inside the array are not (unless you declare an array of pointers).
o You cannot dereference a value variable : cannot int x and then *x = 6
o
Know whether you are dealing with a pointer or a
value variable, and be able to set address or value as appropriate for the
problem you are solving
§
Ex: scanf does not
need the & for a pointer
§ Ex: printf does need a * for a pointer when not using %p so the pointed at value can print
· Pass to functions:
o Passing a pointer is called passing by reference
o Nothing in C passes by reference without you insisting that a pointer be passed (except you can say arrays naturally pass by pointer because arrays are pointers).
· Pointers and arrays
o An array variable is a pointer, but it also knows the full size of the array
o Making a pointer to an array (such as when you pass an argument to a function) only knows the size of the pointer and the address of the first element of the array.
o Pointers to arrays can use pointer arithmetic, moving through elements by adding 1.
o A dynamic array is created by using malloc to allocate the memory for the array, and then putting the address malloc returns into a pointer.
o For multidimensional dynamic arrays, malloc the memory for the array of pointer to each row, and then malloc each row. Remember to free all that you create.
Typedef:
· Like creating a variable type name, but really just substitute words
o Ex:
§ In heading of program: typdef int * IntPtr
§ Later use: IntPtr x
§
Means: int * x