270 likes | 412 Views
C Programming – Part 5 Pointers. TEC 284. What are Pointers?. One of the most challenging topics in C programming Powerful structures used in C to work with variables, functions and data structures through their memory addresses
E N D
C Programming – Part 5 Pointers TEC 284
What are Pointers? • One of the most challenging topics in C programming • Powerful structures used in C to work with variables, functions and data structures through their memory addresses • Pointer variables contain memory addresses that point to other variables • Let’s look at an example to clarify the previous statement
Pointers int num = 10; //memory address 0x1234 int *ptr; // declares a pointer that points to the memory address of an integer ptr = # //pointer now points to memory address 0x1234 • The indirection operator (*) in front of a variable is used to declare a pointer
Pointers and memory addressing Source: C Programming Second Edition – Michael Vine
Pointer initialization int *ptr; int *ptr2; int *ptr3; //this is correct ptr = &x; ptr2=0; ptr3=NULL; • Pointer variables can only be assigned memory addresses, 0 or NULL • #include <stdio.h> • main() { • int x = 5; • int *iPtr; • iPtr = 5; //this is wrong • iPtr = x; // this is also wrong • }
Pointer initialization • You can assign non-address values to pointers by using the indirection operator (*) int x = 5; int *iPtr; iPtr = &x; // iPtr points to the memory address of the variable x and *iPtr = 7; // variable x is indirectly assigned the value of 7
Printing pointer variable contents • Print the memory address of pointers and non-pointer variables using the %p conversion specifier int x = 1; int *iPtr; *iPtr = 5; printf(“\n*iPtr = %p\n &x = %p\n”, iPtr, &x); This will result in: *iPtr = 0x22cce4; &x = 0x22cce4;
Printing pointer variable contents int x = 5, y = 10, *iPtr = NULL; printf (“\niPtr points to: %p\n”, iPtr); //assign memory address of y to pointer iPtr = &y; printf(“\niPtr now points to: %p\n”,iPtr); //change the value of x to the value of y x=*iPtr; printf(“\nThe value of x is now: %d\n”,x); //change the value of y to 15 *iPtr = 15; printf(“\nThe value of y is now: %d\n”,y); The output of this program will be: iPtroints to : 0x0 iPtr now points to : 0x22cce0 The value of x is now 10 The value of y is now 15
Functions and Pointers • By default arguments are passed by value in C • Pointers give the ability to pass arguments by reference • Passing by value involves making a copy of the incoming argument for the function to use • This may not be an efficient use of memory (especially in situations where memory is limited e.g. Arduino Micontroller)
Pass by value void demoPassByValue(int); //function prototype main() { int x=0; printf(“\nEnter a number”); scanf(“%d”,&x); demoPassByValue(x); printf(“\nThe original value of x did not change: %d\n”,x); } //end main void demoPassByValue(int x) { x+=5; printf(“\nThe value of x is: %d\n”, x); }// end demoPassByValue If a number 65 is entered, result is: The value of x is: 70 The original value of x did not change: 65
Pass by reference void demoPassByReference(int *); //function prototype main() { int x=0; printf(“\nEnter a number”); scanf(“%d”,&x); demoPassByReference(&x); printf(“\nThe changed value of x is: %d\n”,x); } //end main void demoPassByReference(int *ptrX) { *ptrX+=5; printf(“\nThe value of x is now: %d\n”, *ptrX); }// end demoPassByValue If a number 60 is entered, result is: The value of x is now: 65 The changed value of x is: 65
Caution • If you forget to place the indirection (*) operator in front of a pointer in a print statement that displays a number with the %d conversion specifier, C will print out the memory address of the pointer //This is wrong printf(“\nThe value of x is now: %d\n”, ptrX); //This is right printf(“\nThe value of x is now: %d\n”, *ptrX);
Passing arrays to functions • Arrays are groupings of continguous memory segments • The array name is a pointer to the first memory location in the continguous memory segment • Assigning an array name to a pointer assigns the first memory location of the array to the pointer variable
Passing arrays to functions intiArray[5] = {1,2,3,4,5}; int *iPtr = iArray; printf(“\nAddress of pointer: %p\n”, iPtr); printf(“First address of array: %p\n”, &iArray[0]); printf(“\nPointer points to: %d\n”, *iPtr); printf(“First element of array contains: %d\n”, iArray[0]); The result is: Address of pointer: 02x22cc00 First address of array: 02x22cc00 Pointer points to: 1 First element of array contains: 1
Passing arrays to functions • Knowing that an array name contains a memory address that points to the first element in the array, array names can be treated like a pointer when passing arrays to functions • You don’t have to use & (the unary operator) • Arrays passed as arguments to functions are thus passed be reference automatically
Arrays passed by reference void squareNumbers(int []); //function prototype main() { int x, iNumbers[3] = {2,4,6}; printf(“\nThe current array values are:\n “); for(x=0;x<3;x++) { printf(“%d ”, iNumbers[x]); //prints the contents of the array printf(“\n”); } squareNumbers(iNumbers); printf(“\nThe modified array values are:\n “); for(x=0;x<3;x++) { printf(“%d ”, iNumbers[x]); //print modified array contents printf(“\n”); } } // end main void squareNumbers(int num[]) { for (x=0; x <3; x++ ) { num[x] *= num[x]; } } //end square numbers
Arrays passed by reference Result is: The current array values are: 2 4 6 The modified array values are: 4 16 36
Pointers and Arrays • Pointers and Arrays are very closely linked in C int x, a[10], *pa; pa = &a[0]; // This is the same as pa = a; pa is a pointer to the address of a[0] • a[i] can be written as *(a + i) • &a[i] is equal to a +i • pa[i] is equal to *(pa + i)
How arrays and pointers are different • A pointer is a variable • You can do pa = a and pa++ • An array is not a variable • a = pa or a++ is illegal
Array/Pointer concepts • strlen(s) is exactly equal to strlen(&s[0]) • The following two declarations are identical • int strlen(char s[]) • int strlen(char *s) int strlen(char *s) { char *p = s; while (*p != '\0'){ p++; } return p-s; }
Array/Pointer concepts void strcpy(char *s, char *t) { while ( (*s++ = *t++) != '\0');}
const Qualifier • Arguments can be passed to functions in one of 2 ways • Pass By Reference • Pass By Value • Pass By Value is good in that it ensures original values can’t be modified and provides encapsulation (“information hiding”) inside a function. It however creates additional memory overhead • Pass By Reference provides the capability to modify argument contents via pointers • There may be a case where you want power and speed of pass by reference without security risk of changing a variable’s contents
const Qualifier • This can be achieved with the const Qualifier • const allows you to create read-only variables • const can be used with pointers to create a read-only argument while still achieving pass by reference Syntax: void printArgument(const int *);
const Example void modifyArray(const int[]); main() { int iNumbers[3] = {2,4,6}; modify(iNumbers); } // end main void modifyArray(const int num[]) { int x; for (x=0; x<3; x++) num[x]= num[x] * num[x]; //THIS will not compile – num is read-only }
Function Prototypes Specifies the interface for a function http://en.wikipedia.org/wiki/Function_prototype
Question 1 • Write a C function which takes three arguments (a, b and c) and rotates the values that are stored so that value a goes to b, b goes to c and c goes to a • Starting point: void switch(int *a, int *b, int *c) { }
Question 2 • Write a C program to read through an array of any type using pointers. Write a C program to scan through this array to find a particular value.