Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

Similar presentations


Presentation on theme: "1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation."— Presentation transcript:

1 1 Pointers

2 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such as binary trees and linked lists.

3 3 What Are Pointers A pointer is the memory address of an object. A pointer variable is a variable that is specifically declared to hold a pointer to an object of its specified type. This address is the location of another object (typically another variable) in memory.

4 4 1003 Variable in memory Memory address 1000 1001 1002 1003 1004 1005......

5 5 Pointer Declaration General syntax: type *name; int *m; //The variable m can hold a //pointer to type int. char *ch; int count, *y, q;

6 6 Two Pointer Operators Address Operator: & Dereference Operator: * Both & and * have a higher precedence than all other arithmetic operators except the unary minus, with which they share equal precedence.

7 7 & Operator The & is a unary operator that returns the memory address of its operand. & “the address of” m = &count; m receives the address of count. m count 100

8 8 * Operator * is the complement of &. It is a unary operator that returns the value located at the address that follows. * “at address” q = *m; q receives the value at address m. ?

9 9 #include int main(void) { int target, source=10; int *m; m = &source; target = *m; printf("%d", target); return 0; } Put the value 10 into a variable called target.

10 10 Pointer Assignments You can use a pointer variable on the right-hand side of an assignment statement to assign its value to another pointer. When both pointers are the same type, the situation is straightforward.

11 11 #include int main(void) { int x = 99; int *p1, *p2; p1 = &x; p2 = p1; printf("%p %p", p1, p2); printf(''%d %d\n", *p1, *p2); return 0; }

12 12 Illustrates Distinction between a pointer var value & a Dereferenced var. main( ) {int i = 777, *p = &i; printf (“value of i:%d\n”, *p); printf (“Addr of i:%u or %p\n”, p, p); } OutputValue of i: 777 Address of i: 234880259 or dfffcfc u - (unsigned Dec integer) p - (whatever way is Default for system) - Here is Hex.

13 13 Example 1 int i = 1, *j, *k; Assume addresses of i, j, k are respectively Byte addresses 10, 20, 30 i:10j:20k:30 1.j = &i; int varPointer varPointer var i:10j:20k:30 10? ?1? 1

14 14 2. *j = 2; i:10j:20k:30 Stores 2 at the memory location pointed to by j. 3. i = *j + 1; i:10j:20k:30 * has higher precedence than +. Assigns to i the contents of the location pointed to by j, incremented by 1. 10? 1 210? 12 3

15 15 4. k = &i; i:10j:20k:30 5.printf (“%d”, *k); output:3 103

16 16 int a=42, b=53, *p1, *p2; p1 = &a; p2 = p1; p2 = &b; p1? p2? *p1? *p2? Example 2

17 17 p1 p2 ? ? int a=42, b=53, *p1, *p2; p1 = &a; p1 p2 ? 42 p2 = p1; p1 p2 42 p1 p2 42 p2 = &b; 42 53

18 18 int *p1, v1; v1 = 0; p1 = &v1; *p1 = 42; v1? p1? *p1? int a=8, b=9; int *p1, *p2; p1 = &a; p2 = &b; p1 = p2; vs. *p1 = *p2; Example 3

19 19 p1 p2 8 9 beforeafter p1 p2 8 9 p1 p2 8 9 beforeafter p1 p2 9 9 p1 = p2; *p1 = *p2;

20 20 Example 4 # include main( ) { int j, i, *intptr; scanf(“%d%d”, &i, &,j); intptr = i > j ? &i:&j; printf(“%d\n”, *intptr); } Address of the larger var is stored in ? : then the larger number is output.

21 21 Example 5 int a=3,b=7,*p;p = &b; a b p *p=2**p–a; printf (“b= %d\n”, b); “The object pointed to by p (i.e., b) is assigned the value of 2**p–a.” 1) 2 * *p 2 * 7 2) 14 – 3 11 3) Which is assigned? b 3 7 11

22 22 int i, *p = &i;correct int *p = &i, i;sequence wrong. The variable must be defined before the address can be assigned. Pointer Initialization

23 23 p = &i; p “points to” i p = 0; “Null” is usually defined as 0. p = NULL; Pointer constant points “nowhere”. p = (int *) 1307; cast to pointer to int. 1307 is an absolute address in memory.

24 24 int i = 3, j = 5, *p = &i, *q = &j, *r; double x; r ? i:10 j p:50 q x 1) p = i + 7;The only integer value that can be assigned to a pointer variable directly is the special value 0 (NULL). To assign any other value requires a cast (int *) (i + 7) 3 5 ILLEGAL ?

25 25 2)**&p All are unary operators.&p -The address of p (50). *&p -“The Addr stored at p” (10) i:10p:5 **&p – The contents of the address (*&p) “The contents of the variable pointed to by p” i.e., 3 3 1 2 10 3

26 26 3) r = &x;Illegal Why? x is a double variable r is pointer to int. 4) 7 * *p / *q + 7 i:10 j Dereference Right to Left p q 1. *q 5 2. *p 3 3. 7 * 3 [21] 4. 21/5 4 5 4 + 7 11 3 5

27 27 5) *(r = &j) *= *p 4 2 1 5 3j - int var p - pointer to int jir - pointer to int r p 1. &j - Address of j 2. r = r points to j 3. *p contents of thing pointed to by p i.e., 3 4. *( ) Location pointed to by r, i.e., j. 5. *= *r *= *p; *r = *r * *p; 3 5 1 1

28 28 int *v=(int *)100;Byte Address. 100v 102v + 1 104v + 2 106v + 3 108v + 4 Pointer Arithmetic assume int are 2 bytes long.

29 29 char *ch=(char *)3000; int *i=(int *)3000; 3000 3001 3003 3002 3004 3005 ch ch+1 ch+2 ch+3 ch+4 ch+5 i i+1 i+2 Pointer Arithmetic (cont.)

30 30 Pointer Arithmetic (cont.) Only two operations are allowed. –Addition and subtraction. e.g. p++; p--; p1=p1+12; Cannot multiply or divide pointers. Cannot add two pointers. Cannot add or subtract type float or double to or from pointers.

31 31 Call by Reference Passing a ADDRESS of the argument to a formal parameter which is a POINTER of the same type as the argument. Code within the function can change the value of the argument passed to the function.

32 32 Steps 1)Declare a function parameter to be a pointer. 2) Pass an address as an argument when the function is called. 3) Use the dereferenced pointer in the function body to reference the argument in the calling function.

33 33 #include void swap(int *x, int *y); int main (void) { int i=10, j=20; printf("i and j before swapping: %d %d\n", i, j); swap(&i, &j); /* pass the addresses of i and j */ printf("i and j after swapping: %d %d\n", i, j); return 0; }

34 34 void swap(int *x, int *y) { int temp; temp=*x; /* save the value at address x */ *x =*y; /* put y into x */ *y=temp; /* put x into y */ }

35 35 Storage Classes

36 36 Every variable or function in C has 2 attributes: TypeStorage Class General form: storage-specifier type var_name Storage Class : determines how the compiler allocates memory to that variable. Auto Extern Register Static

37 37 Storage Class of a C object defines its: 1)Spatial Territory- Defines where it can be referred to in the program. Its Scope or Visibility. 2)Temporal Authority- Defines when an object is available. The Extent to which it exists.

38 38 Auto Variables The storage class auto can only be used in a block: it cannot be used at the global level. 1)Spatial Limitation(scope): The auto variable is limited to the block in which it is defined and its sub-blocks. LOCAL. 2)Temporal Limitation(extent): Are alive only when the block in which they are defined is running. Variable does not exist before block execution, when block terminates it dies(mortal).

39 39 Impact of Auto Auto is the default SC for local vars because it makes the most efficient use of memory. Good programmers use Auto when ever possible because their lifetime is brief and their scope is limited to one function. They provide an effective way to isolate the actions of each program unit from the others.

40 40 auto Most common of the four storage classes. Variables declared within function bodies are auto by default. Thus auto is rarely explicitly specified. auto int a,b,c; auto float f;

41 41 Unintentional interference between functions is minimized and, making it much easier to debug large programs. Constant allocation and deallocation of auto vars does add some overhead to the the execution time, but since is done quite efficiently, the time wasted is minimal and the advantages of the added modularity are great.

42 42 When a block is entered, the system allocates memory for the auto variables. “LOCAL”i.e., Those declared in the block. When Block is exited the variables are released and their values lost. IF re-enter the Block? _________ Memory is reallocated.

43 43 Call by Reference with Auto Parameters 1) When the block is suspended, such as when it calls another function,the variable is suspended but can still be accessed and changed(e.g. actual argument in a func call). 2) It can still be referenced and changed through a pointer to it. When the block becomes active again, the variable becomes active i.e., can directly reference it by name.)

44 44 Extern Primary purpose is to make variables visible to other compilation units. Must be defined in the global area of a program, that is outside of any block. All global variables( i.e., those defined outside any function) are EXTERN by default. !!!!! EXTERN variables are DANGEROUS and should be used with CAUTION !!!!!

45 45 Extern Characteristics Spatial Limitation(global): It is visible from its definition to the end of the program. It can be referred to and changed by all blocks that come after it as well as by other programs that are aware of its existence. Temporal Limitation(Immortal): The whole life of the program. From the time of its allocation till the end of the program.

46 46 Variables declared outside of a function have extern storage class by default. i.e., even if don’t use keyword extern. Extern Var’s are initialized to 0 automatically. extern - “Look for the variable elsewhere – either in this or another file.” extern (cont.)

47 47 See 3 handouts on program examples Relevant to EXTERN storage class. K-5, K-6, K-7.

48 48 Register Storage Class Variables so declared should be stored in high speed memory i.e., Registers(cpu) provided if is possible to do so. Defaults to Auto if register not available

49 49 Typically, the compiler has only a few such registers available. Many are required for system use & can’t be allocated otherwise: * Base Addr of program * Return Addr after pgm execution ends, * Instruction reg, program counter, etc……..

50 50 It is an attempt to improve execution speed. Most frequently accessed variable – loop control variable or function parameters. register int i ; for (i = d, i <LIMIT, ++i){ … } If storage class is present & Type is absent - get int. register i ;

51 51 Recommendation Don’t Use The standard states that you can’t compute the address of a register. That means you can’t use the address operator or indirection operator(*) with a “Register” variable. Secondly, the compiler may ignore your recommendation.

52 52 Static Storage Class A static variable can be defined inside a block(local) or in the global area of the program. Its characteristics differ slightly depending on where it is defined. We will look at each separately.

53 53 Local Static Variables Static variable is defined inside a block: 1.Spatial Limitation(scope): LOCAL, undefined outside the block. 2.Temporal Limitation(extent): Immortal. It lives as if it were a global variable. What are the consequences of the immortal extent?

54 54 Locally defined Static variables are one of the truly significant features of the “C” language. 1) Allow a “Local variable” to retain its previous value when a block is re-entered. (Not the case with Auto) 2)In other languages, these variables must be declared globally, which reduces the benefits of data hiding and isolation. 3)The variable will be automatically initialized to 0 when allocated.

55 55 Void f(void) { static int cnt = 0; ++ cnt; if (cnt % 2 == 0)... else..... } * 1st Time Function Invoked cnt is set to 0. * Upon EXIT cnt NOT cleared from memory * Next invocation,retains previous value.

56 56 Global Static Variables Global variables-that is, variables defined outside the scope of all blocks-can be referred to by other compilation units. To prevent a global variable from being exported to the LINKER for reference by other compilation units, it can be declared static.

57 57 Global Static Characteristics : 1)Spatial Limitation(scope): Global. Visible from its definition to the end of the compile unit. Guarantees that the scope does not extend beyond its spatial area, i.e., the current complilation unit. 1)Temporal Limitation(extent) Immortal. Same as local static, it lives as global variables live.

58 58 Static Extern Variable Restricted in scope to the “remainder of the file” in which they are defined. Not known to other files(compilation units). void f(void) { …… /* v not available here */ } static int v; void g(void) } …… /* v can be used here */ }

59 59 A Function can be Static: The scope of the function is limited to this file only(privacy concern). Is known throughout the entire file. void f(int a) { …….. /* g() is available here, } but not in other files */ static int g(void) { …….. }

60 60 Default Initialization Extern & Static vars are initialized to 0 by the system. Auto & Register are usually not initialized by system. Start will garbage.

61 61 Type Qualifiers Two type qualifiers: const volatile They are used in declarations and must be coded after the storage class but precede the type names that they qualify. static const int k = 3; Control how variables may be accessed or modified.

62 62 const Variables of type const may not be changed by your program. The compiler is free to place variables of this type into read-only memory (ROM). const int a=10; const int a=7; int *p=&a; //wrong const int a=7; const int *p=&a; //correct

63 63 #include void sp_to_dash(const char *str); int main(void) { sp_to_dash("this is a test"); return 0; } void sp_to_dash(const char *str) { while(*str) { if(*str= = ' ') printf("%c", '-'); if(*str= =' ') *str= '-'; wrong else printf("%c", *str); str++; } }

64 64 Volatile The modifier volatile tells the compiler that a variable's value may be changed in some unspecified way by the hardware. –For example, a global variable's address may be passed to the operating system's clock routine and used to hold the system time. –Programmers use Volatile objects in advanced systems programming(beyond our scope).

65 65 Declaration vs. Definition In General, a Declaration is a program element that provides a compiler with essential information or useful advice. When you specify the type of a variable or parameter you are said to declare variable or parameter.

66 66 A definition causes a compiler to set aside memory at compile time (every variable definition is a declaration) - not always the reverse. e.g. when you introduce a variable outside of any function definition (global variable), you both declare and define the variable, because you have: a) informed the compiler about the variable’s type. b) caused the compiler to set aside memory for the variable at compile time.

67 67 When you introduce a variable inside a function definition(local), you only declare that variable, because the compiler does not set aside memory for such variable at compile time [memory in stack frame]. Functions are both declared & defined Because: a) must specify return type. b) compiler sets aside memory for functions at compile time.


Download ppt "1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation."

Similar presentations


Ads by Google