C language - Lecture 6, Page 1 BIL 104E INTRODUCTION TO...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Lecture 6, Page 1 BIL 104E INTRODUCTION TO SCIENTIFIC AND ENGINEERING COMPUTING Compiled by Ergin TARI Lecture 6, Page 2 INFORMATION TO USERS THE NOTES IN THE FOLLOWING SLIDES ARE COMPILED FROM FREE VERSIONS OF THE BOOKS Sams Teach Yourself C in 21 Days (Sams Teach Yourself) By Peter Aitken and Sams Teach Yourself C in 24 Hours (Published by Sams) By Tony Zhang. The electronic versions of these and other books can be found in the web pages including http://server11.hypermart.net/davidbook901/data/c/c1f8c0d9.htm http://www.informit.com/itlibrary http://www.free-book.co.uk/computers-internet/programming/c/ http://aelinik.free.fr/c/ Compiled by Ergin TARI Lecture 6, Page 3 BIL104E: Introduction to Scientific and Engineering Computing, Summer 2007 Lecture 6 Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators Compiled by Ergin TARI Lecture 6, Page 4 Introduction Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings But what is a pointer? A pointer is a variable whose value is used to point to another variable. From this definition, you know two things: first, that a pointer is a variable, so you can assign different values to a pointer variable, and second, that the value contained by a pointer must be an address that indicates the location of another variable in the memory. That's why a pointer is also called an address variable. Compiled by Ergin TARI Lecture 6, Page 5 A program variable is stored at a specific memory address. 1:#include <stdio.h> 2:int main() 3:{ 4: float fl=3.14; 5: printf("%.2f\n", fl); 6: return 0; 7:} Compiled by Ergin TARI Lecture 6, Page 6 A program variable is stored at a specific memory address. A variable named rate has been declared and initialized to 100. The compiler has set aside storage at address 1004 for the variable and has associated the name rate with the address 1004. Compiled by Ergin TARI Lecture 6, Page 7 Creating a Pointer You should note that the address of the variable rate (or any other variable) is a number and can be treated like any other number in C. If you know a variable's address, you can create a second variable in which to store the address of the first. The first step is to declare a variable to hold the address of rate. Give it the name p_rate, for example. At first, p_rate is uninitialized. Storage has been allocated for p_rate, but its value is undetermined. Memory storage space has been allocated for the variable p_rate Compiled by Ergin TARI Lecture 6, Page 8 Creating a Pointer The next step is to store the address of the variable rate in the variable p_rate. Because p_rate now contains the address of rate, it indicates the location where rate is stored in memory. In C parlance, p_rate points to rate, or is a pointer to rate. The variable p_rate contains the address of the variable rate and is therefore a pointer to rate Compiled by Ergin TARI Lecture 6, Page 9 Pointer Variable Declarations and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) count 7 Pointers contain address of a variable that has a specific value (indirect reference) Indirection referencing a pointer value countPtr count 7 Compiled by Ergin TARI Lecture 6, Page 10 Pointer Variable Declarations and Initialization Pointer declarations * used with pointer variables int *myPtr; Declares a pointer to an int (pointer of type int *) Multiple pointers require using a * before each variable declaration int *myPtr1, *myPtr2; Can declare pointers to any data type char *ptr_c; int *ptr_int; float *ptr_flt; /* declare a pointer to a character */ /* declare a pointer to an integer */ /* declare a pointer to a floating-point */ Initialize pointers to 0, NULL, or an address 0 or NULL points to nothing (NULL preferred) Compiled by Ergin TARI Lecture 6, Page 11 Initializing Pointers Like regular variables, uninitialized pointers can be used, but the results are unpredictable and potentially disastrous. Until a pointer holds the address of a variable, it isn't useful. The address doesn't get stored in the pointer by magic; your program must put it there by using the address-of operator, the ampersand (&). When placed before the name of a variable, the address-of operator returns the address of the variable. Therefore, you initialize a pointer with a statement of the form pointer = &variable; The program statement to initialize the variable p_rate to point at the variable rate would be p_rate = &rate; /*assign the address of rate to p_rate*/ Before the initialization, p_rate didn't point to anything in particular. After the initialization, p_rate is a pointer to rate. Compiled by Ergin TARI Lecture 6, Page 12 Pointer Operators & (address operator) Returns address of operand int y = 5; int *yPtr; yPtr = &y; yPtr "points to" y y 5 yptr 500000 600000 600000 y 5 // yPtr gets address of y yPtr Address of y is value of yptr Compiled by Ergin TARI Lecture 6, Page 13 Address (Left Value) Versus Content (Right Value) As you might know, the memory inside your computer is used to hold the binary code of your program, which consists of statements and data, as well as the binary code of the operating system on your machine. Each memory location must have a unique address so that the computer can read from or write to the memory location without any confusion. When a variable is declared, a piece of unused memory will be reserved for the variable, and the unique address to the memory will be associated with the name of the variable. The address associated with the variable name is usually called the left value of the variable. Then, when the variable is assigned a value, the value is stored into the reserved memory location as the content. The content is also called the right value of the variable. For instance, after the integer variable x is declared and assigned to a value like this: int x; x = 7; The variable x now has two values: Left value: 1000 Right value: 7 Here the left value, 1000, is the address of the memory location reserved for x. The right value, 7, is the content stored in the memory location. Note that depending on computers and operating systems, the right value of x can be different from one machine to another. Compiled by Ergin TARI Lecture 6, Page 14 The Address-of Operator (&) Cont. The C language even provides you with an operator, &, in case you want to know the left value of a variable. This operator is called the address-of operator because it can return the address (that is, the left value) of a variable. The following code, for example, long int x, y; y = &x; assigns the address of the long integer variable x to another variable, y. Compiled by Ergin TARI An Example of "Address of" Operator Code Output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <stdio.h> main(){ char c; int x; float y; Lecture 6, Page 15 c: address=0x1AF4, content=@ x: address=0x1AF2, content=-32557 y: address=0x1AF6, content=0.00 c: address=0x1AF4, content=A x: address=0x1AF2, content=7 y: address=0x1AF6, content=123.45 printf("c: address=0x%p, content=%c\n", &c, c); printf("x: address=0x%p, content=%d\n", &x, x); printf("y: address=0x%p, content=%5.2f\n", &y, y); c = 'A'; x = 7; y = 123.45; printf("c: address=0x%p, content=%c\n", &c, c); printf("x: address=0x%p, content=%d\n", &x, x); printf("y: address=0x%p, content=%5.2f\n", &y, y); return 0; } Compiled by Ergin TARI Lecture 6, Page 16 ANALYSIS of the previous program The statement in line 8 displays the address (that is, the left value) and the content (that is, the right value) of the character variable c on the screen. Here the &c expression returns the address of c. Note that the format specifier %p is used in the printf() function of line 9 for displaying the address returned from &c. Likewise, lines 9 and 10 print out the addresses of x and y, as well as the contents of x and y. From the first part of the output, you see that the addresses (in hex format) of c, x, and y are 0x1AF4, 0x1AF2, and 0x1AF6. Because these three variables have not been initialized yet, the contents contained in their memory locations are what is left there from the last memory writing. However, after the initializations that are carried on in lines 11_13, the memory slots reserved for the three variables have the contents of the initial values. Lines 14_16 display the addresses and contents of c, x, and y after the initialization. You can see in the second part of the output, the contents of c, x, and y are now `A', 7, and 123.45, respectively, with the same memory addresses. Compiled by Ergin TARI Lecture 6, Page 17 Using Pointers The indirection operator (*) comes into play again. When the * precedes the name of a pointer, it refers to the variable pointed to. If continue with the previous example, in which the pointer p_rate has been initialized to point to the variable rate. If you write *p_rate, it refers to the variable rate. If you want to print the value of rate (which is 100 in the example), you could write printf("%d", rate); or this: printf("%d", *p_rate); In C, these two statements are equivalent. Accessing the contents of a variable by using the variable name is called direct access. Accessing the contents of a variable by using a pointer to the variable is called indirect access or indirection. Compiled by Ergin TARI Lecture 6, Page 18 printf("%d", rate); or this: printf("%d", *p_rate); a pointer name preceded by the indirection operator refers to the value of the pointed-to variable. Compiled by Ergin TARI 1: /* Demonstrates basic pointer use. */ 3: #include <stdio.h> 4: 5: /* Declare and initialize an int variable */ 7: int var = 1; 8: 9: /* Declare a pointer to int */ 10: 11: int *ptr; 12: 13: main() 14: { 15: /* Initialize ptr to point to var */ 16: 17: ptr = &var; 18: 19: /* Access var directly and indirectly */ 20: 21: printf("\nDirect access, var = %d", var); 22: printf("\nIndirect access, var = %d", *ptr); 23: 24: /* Display the address of var two ways */ 25: 26: printf("\n\nThe address of var = %d", &var); 27: printf("\nThe address of var = %d\n", ptr); 28: 29: return 0; 30: } Lecture 6, Page 19 Direct access, var = 1 Indirect access, var = 1 The address of var = 4264228 The address of var = 4264228 The address reported for var might not be 4264228 on your system. Compiled by Ergin TARI Lecture 6, Page 20 If you have a pointer named ptr that has been initialized to point to the variable var, the following are true: *ptr and var both refer to the contents of var (that is, whatever value the program has stored there). ptr and &var refer to the address of var. A pointer name without the indirection operator accesses the pointer value itself, which is, of course, the address of the variable pointed to.x Compiled by Ergin TARI Lecture 6, Page 21 Pointer Operators Cont. yPtr = &y; * (indirection/dereferencing operator) Returns a synonym/alias of what its operand points to *yptr returns y (because yptr points to y) * can be used for assignment Returns alias to an object *yptr = 7; // changes y to 7 Dereferenced pointer (operand of *) must be an lvalue (no constants) * and & are inverses They cancel each other out Compiled by Ergin TARI 1: #include <stdio.h> c: address=0x1B38, content=A 2: x: address=0x1B36, content=7 3: main() { y: address=0x1B32, content=123.45 4: char c, *ptr_c; 5: ptr_c: address=0x1B30, content=0x1B38 int x, *ptr_x; 6: float y, *ptr_y; *ptr_c => A 7: ptr_x: address=0x1B2E, content=0x1B36 8: c = `A'; 9: *ptr_x => 7 x = 7; 10: ptr_y: address=0x1B2C, content=0x1B32 y = 123.45; 11: printf("c: address=0x%p, content=%c\n", &c, c); *ptr_y => 123.45 12: printf("x: address=0x%p, content=%d\n", &x, x); 13: printf("y: address=0x%p, content=%5.2f\n", &y, y); 14: 15: ptr_c = &c; 16: printf("ptr_c: address=0x%p, content=0x%p\n", &ptr_c, ptr_c); 17: printf("*ptr_c => %c\n", *ptr_c); 18: ptr_x = &x; 19: printf("ptr_x: address=0x%p, content=0x%p\n", &ptr_x, ptr_x); 20: printf("*ptr_x => %d\n", *ptr_x); 21: ptr_y = &y; 22: printf("ptr_y: address=0x%p, content=0x%p\n", &ptr_y, ptr_y); 23: printf("*ptr_y => %5.2f\n", *ptr_y); 24: return 0; 25: 26: } Declaring and assigning values to pointersLecture 6, Page 22 Compiled by Ergin TARI Lecture 6, Page 23 Output c: address=0x1B38, content=A x: address=0x1B36, content=7 y: address=0x1B32, content=123.45 ptr_c: address=0x1B30, content=0x1B38 *ptr_c => A ptr_x: address=0x1B2E, content=0x1B36 *ptr_x => 7 ptr_y: address=0x1B2C, content=0x1B32 *ptr_y => 123.45 Compiled by Ergin TARI 1 /* Fig. 7.4: fig07_04.c Lecture 6, Page 24 2 Using the & and * operators */ 3 #include <stdio.h> 4 1. Declare variables 5 int main() The address of a is the value 6 { 7 int a; /* a is an integer */ of aPtr. 2 Initialize variables 8 int *aPtr; /* aPtr is a pointer to an integer */ 9 The * operator returns an 10 a = 7; 3. Print 11 aPtr = &a; /* aPtr set to address of a */ alias to what its operand 12 points to. aPtr points to a, 13 printf( "The address of a is %p" so *aPtr returns a. 14 "\nThe value of aPtr is %p", &a, aPtr ); 15 16 printf( "\n\nThe value of a is %d" 17 "\nThe value of *aPtr is %d", a, *aPtr ); 18 19 printf( "\n\nShowing that * and & are inverses of " Notice how * and 20 "each other.\n&*aPtr = %p" & are inverses 21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr ); 22 23 return 0; 24 } The address of a is 0012FF88 The value of aPtr is 0012FF88 Program Output Outline The value of a is 7 The value of *aPtr is 7 Proving that * and & are complements of each other. &*aPtr = 0012FF88 *&aPtr = 0012FF88 Compiled by Ergin TARI Lecture 6, Page 25 Null Pointers A pointer is said to be a null pointer when its right value is 0. Remember, a null pointer can never point to valid data. To set a null pointer, simply assign 0 to the pointer variable. For example: char *ptr_c; int *ptr_int; ptr_c = ptr_int = 0; Here ptr_c and ptr_int become null pointers after the integer value of 0 is assigned to them. Compiled by Ergin TARI Lecture 6, Page 26 Updating Variables via Pointers As long as you link up a variable to a pointer variable, you can obtain the value of the variable by using the pointer variable. In other words, you can read the value by pointing to the memory location of the variable and using the dereferencing operator. Compiled by Ergin TARI Example of Updating Variables via Pointers #include <stdio.h> main(){ char c, *ptr_c; c: address=0x1828, content=A ptr_c: address=0x1826, content=0x1828 *ptr_c => A ptr_c: address=0x1826, content=0x1828 *ptr_c => B c: address=0x1828, content=B Lecture 6, Page 27 c = 'A'; printf("c: address=0x%p, content=%c\n", &c, c); ptr_c = &c; printf("ptr_c: address=0x%p, content=0x%p\n", &ptr_c, ptr_c); printf("*ptr_c => %c\n", *ptr_c); *ptr_c = 'B'; printf("ptr_c: address=0x%p, content=0x%p\n", &ptr_c, ptr_c); printf("*ptr_c => %c\n", *ptr_c); printf("c: address=0x%p, content=%c\n", &c, c); return 0; } Compiled by Ergin TARI Lecture 6, Page 28 Output c: address=0x1828, content=A ptr_c: address=0x1826, content=0x1828 *ptr_c => A ptr_c: address=0x1826, content=0x1828 *ptr_c => B c: address=0x1828, content=B Compiled by Ergin TARI Lecture 6, Page 29 Pointing to the Same Thing #include <stdio.h> main(){ int x; int *ptr_1, *ptr_2, *ptr_3; x: address=0x1838, content=1234 ptr_1: address=0x1834, content=0x1838 *ptr_1 => 1234 ptr_2: address=0x1836, content=0x1838 *ptr_2 => 1234 ptr_3: address=0x1832, content=0x1838 *ptr_3 => 1234 x = 1234; printf("x: address=0x%p, content=%d\n", &x, x); ptr_1 = &x; printf("ptr_1: address=0x%p, content=0x%p\n", &ptr_1, ptr_1); printf("*ptr_1 => %d\n", * ptr_1); ptr_2 = &x; printf("ptr_2: address=0x%p, content=0x%p\n", &ptr_2, ptr_2); printf("*ptr_2 => %d\n", * ptr_2); ptr_3 = ptr_1; printf("ptr_3: address=0x%p, content=0x%p\n", &ptr_3, ptr_3); printf("*ptr_3 => %d\n", * ptr_3); return 0; } Compiled by Ergin TARI Lecture 6, Page 30 Ouput x: address=0x1838, content=1234 ptr_1: address=0x1834, content=0x1838 *ptr_1 => 1234 ptr_2: address=0x1836, content=0x1838 *ptr_2 => 1234 ptr_3: address=0x1832, content=0x1838 *ptr_3 => 1234 So, a memory location can be pointed to by more than one pointer. Compiled by Ergin TARI Lecture 6, Page 31 #include <stdio.h> main() { char c = 'Q'; char *char_pointer = &c; printf("%c %c\n", c, *char_pointer); c = 'Z'; printf("%c %c\n", c, *char_pointer); *char_pointer = 'Y'; printf("%c %c\n", c, *char_pointer); } Compiled by Ergin TARI QQ ZZ YY Lecture 6, Page 32 #include <stdio.h> main() { int count = 10, x, *int_pointer; /* this assigns the memory address of count to int_pointer */ int_pointer = &count; /* assigns the value stored at the address specified by int_pointer to x */ x = *int_pointer; printf("count = %d, x = %d\n", count, x); } count = 10 , x = 10 Compiled by Ergin TARI Lecture 6, Page 33 #include <stdio.h> main() { int i1, i2, *p1, *p2; i1 = 5; p1 = &i1; i2 = *p1 / 2 + 10; p2 = p1; printf("i1 = %d, i2 = %d, *p1 = %d, *p2 = %d\n", i1, i2, *p1, *p2); } i1 = 5, i2 = 12, *p1 = 5, *p2 = 5 i1 = 5, i2 = 12, *p1 = 5 Compiled by Ergin TARI Lecture 6, Page 34 Summary A pointer is a variable whose value is used to point to another variable. A variable declared in C has two values: the left value and the right value. The left value of a variable is the address; the right value is the content of the variable. The address-of operator (&) can be used to obtain the left value (address) of a variable. The asterisk (*) in a pointer declaration tells the compiler that the variable is a pointer variable. The dereference operator (*) is a unary operator; as such, it requires only one operand. The *ptr_name expression returns the value pointed to by the pointer variable ptr_name, where ptr_name can be any valid variable name in C. If the right value of a pointer variable is 0, the pointer is a null pointer. A null pointer cannot point to valid data. You can update the value of a variable referred by a pointer variable. Several pointers can point to the same location of a variable in the memory. Compiled by Ergin TARI Lecture 6, Page 35 Questions and Answers (Q&A) Q: What are the left and right values? A: The left value refers to the address of a variable, and the right value refers to the content stored in the memory location of a variable. There are two ways to get the right value of a variable: use the variable name directly, or use the left value of the variable to refer to where the right value resides. The second way is also called the indirect way. Q: How can you obtain the address of a variable? A: By using the address-of operator, &. For instance, given an integer variable x, the &x expression returns the address of x. To print out the address of x, you can use the %p format specifier in the printf() function. Q: What is the concept of indirection in terms of using pointers? A: Before this hour, the only way you knew for reading from or writing to a variable was to invoke the variable directly. For instance, if you wanted to write a decimal, 16, to an integer variable x, you could call the statement x = 16;. Compiled by Ergin TARI Lecture 6, Page 36 Questions and Answers (Q&A) Q: Can a null pointer point to valid data? A: No. A null pointer cannot point to valid data. This is so because the value contained by a null pointer is 0. You'll see examples of using null pointers in arrays, strings, or memory allocation later. As you learned in this week, C allows you to access a variable in another way--using pointers. Therefore, to write 16 to x, you can first declare an integer pointer (ptr) and assign the left value (address) of x to ptr--that is, ptr = &x;. Then, instead of executing the statement x = 16;, you can use another statement: *ptr = 16; Here the pointer *ptr refers to the memory location reserved by x, and the content stored in the memory location is updated to 16 after the statement is executed. So, you see, making use of pointers to access the memory locations of variables is a way of indirection. Compiled by Ergin TARI ...
View Full Document

This note was uploaded on 11/22/2010 for the course CSE 104 taught by Professor E.t. during the Spring '09 term at Istanbul Technical University.

Ask a homework question - tutors are online