60 likes | 66 Views
Understand pointers in programming, from declaration to dereferencing and syntax review. Learn how to work with pointers efficiently and effectively in C programming.
E N D
Declaring Pointers <type> * ptrName; “ptrName is a variable which contains the address of a variable of type <type>” For example: char *cPtr; int *nPtr1, *nPtr2; void aFunc( int aParam, double *ptrParam); Using Pointers Dereferencing a pointer: *ptrName “Go to the address contained in the variable ptrName” For example: anInt = *myPtr * 4; *lunch = spaghetti + meatballs; Pointer Syntax Review Remember: pointers are variables which store addresses of other variables!
Declaring Pointers <type> * ptr; means that ptr is of type “pointer to <type> or <type> *” void doubleIt(int *p, int x) { *p = 2 * x; } Using Pointers *ptr is the thing that ptr points to, so its type is <type>. ptr is the pointer itself, so its type is <type> *, or pointer to <type>. Getting the address of a variable: &aVar For example: doubleIt(&result, 9); Pointer Syntax Review (2)
myArray[5] myArray[4] myArray[3] myArray[2] myArray[1] myArray[0] Arrays int myArray[6]; • Arrays are merely contiguous memory locations with one name (compare this to a regular variable, which has one location for every name). • When declaring an array, its size must be known at compile-time. myArray
Array Syntax • Arrays are zero-indexed, which means that you can only access elements from 0 to arraySize-1. • This makes starting loop counters at 0 very convenient! int myArray[ARRAY_SIZE]; int index; for(index = 0; index < ARRAY_SIZE; index++) { printf(“%d\n”, myArray[index]); } • For-loops are particularly useful for array accesses
myArray[5] myArray[4] myArray[3] myArray[2] myArray[1] myArray[0] Arrays and Arrays as Parameters • If an array is passed as a parameter to a function, copying each element is a waste of space. • Solution: don’t pass around copies of arrays! • Arrays are implemented in C as automatically de-referenced pointers. • Changes made to an array in a helper function affect the original array. myArray
Array Parameter Syntax • Because arrays are actually pointers, array parameters can use either pointer syntax or array syntax (but using array syntax for arrays is clearer). • If using array syntax, you do not need to include the array size in the parameter list (the compiler will ignore it). However, it’s useful for the programmer to know what the array size is.int myFunc(int x[]) vs. int myFunc(int *x) int myFunc(int x[SIZE]) vs. int myFunc(int x[]) • Array arguments cannot be passed with the brackets! int arr[ARRAY_SIZE]; myFunc(arr); /* Argument is an array of ints */ myFunc(arr[ARRAY_SIZE]); /* ERROR: type is int! */