Download presentation
Presentation is loading. Please wait.
1
1 Chapter 8 Functions, Pointers, and Storage Classes Pointer Pointers to void Call-by-Reference Basic Scope Rules Storage Classes Default Initialization Function Declarations and Definitions The Type Qualifiers const and volatile
2
2 Given a variable, Date type set aside an appropriate amount of memory instruct the machine to perform specified operations correctly. Where can we use this variable in the code? The scope of the variable During the program execution, when is the memory allocated to the variable and when is the memory released? The lifetime of the variable Storage Class
3
3 Storage Classes DeclarationscopeLife Time Local GlobalTemporarypermanent Autowithin a Block block in which it is declared Memory is allocated when the block is entered and released when the block is exited ExternOutside a function All the functions declared after it The whole execution (Storage is permanently assigned) Register(register ) within a block Block in which it is declared Memory is allocated when the block is entered and released when the block is exited Static(static) within a block Block in which it is declared The whole execution (storage is permanently assigned) Static extern (static) outside a function The remainder of the file in which it is declared The whole execution (Storage is permanently assigned)
4
4 Default Initialization #include int e2=1; void f(){ static int s4=1; printf("%d\n", a); } static int se5=1; int main(void){ int a1=1; register r3=2; f(); }
5
5 Outline Pointer Pointers to void Call-by-Reference Scope Rules Storage Classes Default Initialization Function Declarations and Definitions The Type Qualifiers const and volatile
6
6 Default Initialization Default Initialization Both external variables and static variables that are not explicitly initialized by the programmer are initialized to zero by the system.
7
7 Default Initialization Default Initialization Automatic and register variables usually are not initialized by the system Start with garbage values. Although some C systems do initialize automatic variables to zero, this feature should not be relied on.
8
8 Default Initialization #include int i; void f(){ static int a; printf("%d\n", a); } int main(void){ int b; printf("%d\n", b); printf("%d\n", i); f(); } % a.out -4261900 0 0 Extern, static zero value Automatic, register usually are not initialized by the system Start with garbage values.
9
9 Outline Pointer Pointers to void Call-by-Reference Scope Rules Storage Classes Default Initialization Function Declarations and Definitions The Type Qualifiers const and volatile
10
10 End of Chapter 8 Read 8.1 – 8.14
11
11 Review of Chapter 8 Functions, Pointers, and Storage Classes
12
12 Outline Pointer Pointers to void Call-by-Reference Basic Scope Rules Storage Classes Default Initialization Function Declarations and Definitions The Type Qualifiers const and volatile
13
13 What is pointer? Pointers: Pointer variables can be declared in programs and then used to take addresses as values Declaration odouble *pb, x; Assignment opb = &x; Dereferencing oAccess the value of the variable to which the pointer points by dereference operator *: *pb = 3; The value of x is 3. *pointer pointer = address; DataType *pointer1, *pointer2;
14
14 The legal range of pointer Pointers: What is the legal range of values of any pointer? a set of positive integers that are interpreted as machine addresses on a particular C system, and the special address NULL, 0 ostdio.h: #define NULL 0 oNULL can be used to represent false while(NULL) printf(“loop\n”);
15
15 Pointers to void In ANSI C, one pointer can be assigned to another only when they both have the same type, or when one of them is of type pointer to void void * can be considered as a generic pointer type NULL can be assigned to any pointer. Example: int *p; double *q; void *v; p = NULL; p = (int *) 1; p = v = (int *) q; p = q; p =1; /* legal */ /* illegal */
16
16 Call-by-Reference #include void swap(int*, int* ); int main(void){ int a=3, b=7; printf("Addr %u, %u\n", &a,&b); swap(&a,&b); printf("main: %d %d\n", a, b); return 0; } void swap(int *a, int *b){ int tmp; tmp = *a; *a = *b; *b = tmp; printf("swap: %d %d\n", *a, *b); } How to modify the values of the variables referred to in the argument list? Declaring a function parameter to be a pointer Using the pointer in the function body Passing an address as an argument when the function is called
17
17 Outline Pointer Pointers to void Call-by-Reference Basic Scope Rules Storage Classes Default Initialization Function Declarations and Definitions The Type Qualifiers const and volatile
18
18 Given a variable, Date type set aside an appropriate amount of memory instruct the machine to perform specified operations correctly. Where can we use this variable in the code? The scope of the variable During the program execution, when is the memory allocated to the variable and when is the memory released? The lifetime of the variable Storage Class
19
19 Storage Classes DeclarationscopeLife Time Local GlobalTemporarypermanent Autowithin a Block block in which it is declared Memory is allocated when the block is entered and released when the block is exited ExternOutside a function All the functions declared after it The whole execution (Storage is permanently assigned) Register(register ) within a block Block in which it is declared Memory is allocated when the block is entered and released when the block is exited Static(static) within a block Block in which it is declared The whole execution (storage is permanently assigned) Static extern (static) outside a function The remainder of the file in which it is declared The whole execution (Storage is permanently assigned)
20
20 Default Initialization Default Initialization external variables and static variables that are not explicitly initialized by the programmer are initialized to zero by the system. Automatic and register variables usually are not initialized by the system Start with garbage values. Although some C systems do initialize automatic variables to zero, this feature should not be relied on.
21
21 End of Review Read 8.1 – 8.14
22
22 Chapter 9 Arrays and Pointers
23
23 Chapter 9 Arrays and Pointers One-dimensional arrays The Relationship between Arrays and Pointers Pointer Arithmetic and Element Size Passing Arrays to Functions Two-Dimensional Arrays Multidimensional Arrays Dynamic Memory Allocation
24
24 One-Dimensional Arrays Program Problem: Calculate the average score for the students. Input the score for each student Calculate the sum of scores Calculate the average score Print out the average score Key Point: How to represent the scores using variables in the code? oAssign values to the varaibles representing the scores oAccess the scores when calculating sum and average
25
25 One-Dimensional Arrays #include int main(void){ int s1, s2, s3; int i, avg, sum = 0; printf("Input scores:\n"); printf("#%2d: ", 1); scanf("%d", &s1); printf("#%2d: ", 2); scanf("%d", &s2); printf("#%2d: ", 3); scanf("%d", &s3); sum = s1 + s2 + s3; avg = sum/ 3; printf("Average=%d\n", avg); } First consider 3 scores: Declare variables to store the scores: s1, s2, s3. Get input for each score. Calculate the sum of scores. Calculate the average score. Print out result. What if the number of scores is large, say, 100? Define 100 variables? Calculate the sum of these 100 variables?
26
26 One-Dimensional Arrays Calculate the average score for 100 students. How to declare variables to store the 100 scores? 100 variables? One variable which contains 100 elements. odata type : array Get input for each score Calculate the sum of scores Calculate the average score Print out the average score No
27
27 One-Dimensional Arrays How to declare a variable which contains 100 elements? An array of 100 int: int grade[100] Get input for each grade How to access each element? elements are indexed from 0 the ith element: grade[i] the address of the ith element: &grade[i] Calculate the sum of scores: Calculate the average score Print out the average score #define NUM 100 #include int main(void){ int grade[NUM]; int i, avg, sum = 0; printf("Input scores:\n"); for (i=0; i<NUM; i++){ scanf("%d", &grade[i]); } for (i=0; i<NUM; i++) sum = sum + grade[i]; avg = sum/ NUM; printf("Average=%d\n", avg); }
28
28 One-Dimensional Arrays What is an array? A sequence of data items that are of the same type, that can be indexed, and that are stored contiguously.
29
29 One-Dimensional Arrays Declaration of an array Example: int grade[100]; float f[10000]; Data_Type: the type of elements array_name: the name of the array Size: constant integral expression osize of the array oThe number of elements of the array Data_type array_name[size] Array is a sequence of data items that are of the same type, that can be indexed, and that are stored contiguously.
30
30 One-Dimensional Arrays #define NUM 100 #include int main(void){ int grade[NUM]; int i, avg, sum = 0; printf("Input scores:\n"); for (i=0; i<NUM; i++){ scanf("%d", &grade[i]); } for (i=0; i<NUM; i++) sum = sum + grade[i]; avg = sum/ NUM; printf("Average=%d\n", avg); } Data_type array_name[size]
31
31 One-Dimensional Arrays Declaration of an array (cont’d) the compiler assigns an appropriate amount of memory, starting from a base address int grade[100]; If 4 bytes is used to represent an integer, What is the size of memory assigned to the array? 100 * 4= 400 bytes base address Array is a sequence of data items that are of the same type, that can be indexed, and that are stored contiguously.
32
32 One-Dimensional Arrays Declaration of an array (cont’d) The array name is in effect a pointer constant to this base address. int grade[100]; grade vs. an element in grades: grade[i] ograde is a pointer to the base address, that is, the value of grades is an address; ograde[i] is an integer oIf the 400 bytes is allocated to this array, which starts at memory address 4290704872, what is the value of grade?
33
33 One-Dimensional Arrays #define NUM 100 #include int main(void){ int grade[NUM]; int i, avg, sum = 0; printf("%u\n", grade); for (i=0; i<NUM; i++){ printf("#%2d: ", i+1); scanf("%d", &grade[i]); } for (i=0; i<NUM; i++) sum = sum + grade[i]; avg = sum/ NUM; printf("Average=%d\n", avg); } Memory 4290704872 % a.out 4290704872
34
34 One-Dimensional Arrays Access elements in an array int grade[100]; grade[index] to access an element of the array owhere index is an integral expression Elements are indexed from 0 to size-1 o index must lie in the range 0 to size-1 Example: for (i=0; i<100; i++) sum = sum + grade[i]; Can we access grade[100]? Array is a sequence of data items that are of the same type, that can be indexed, and that are stored contiguously.
35
35 One-Dimensional Arrays #include int main(void){ int a[5]; int i; for( i=0; i<5; i++) a[i]=i; printf("%d %d \n", a[1]+a[2], a[1]-1); } % a.out 3 0
36
36 One-Dimensional Arrays #include int main(void){ int a[5]; int i; for( i=0; i<=5; i++) a[i]=i; printf("%d %d \n", a[1]+a[2], a[1]-1); } index must lie in the range 0 to size-1 What is the potential problem of this code?
37
37 One-Dimensional Arrays Initialization Arrays can be initialized within a declaration An array initializer is a sequence of initializing values written as a brace-enclosed, comma- separated list. Example: int grade[10]={0,0,0,0,0,0,0,0,0,0}; float x[7] = {-1.1, 0.2, 3.0, 4.4, 5.05, 0.0, 7};
38
38 One-Dimensional Arrays #define NUM 10 #include int main(void){ int grade[NUM] = {99,89,89,78,90,87,77,88,99,100}; printf("%d, %d, %d\n", grade[0], grade[1], grade[2]); } 99, 89, 89
39
39 One-Dimensional Arrays Initialization (cont’d) When a list of initializers is shorter than the number of array elements to be initialized, the remaining elements are initialized to zero #define NUM 10 #include int main(void){ int grade[NUM] = {99,89,89}; printf("%d\n", grade[3]); } 0
40
40 One-Dimensional Arrays Initialization (cont’d) If an array is declared without a size and is initialized to a series of values, it is implicitly given the size of the number of initializers. Example: int a[]={3,4,5,6}; is equivalent to int a[4]={3,4,5,6};
41
41 One-Dimensional Arrays #include int main(void){ int grade[] = {99,89,89}; printf("%d\n", sizeof(grade)); } 12
42
42 One-Dimensional Arrays Summary of initialization Arrays can be initialized within a declaration An array initializer is a sequence of initializing values written as a brace-enclosed, comma- separated list. When a list of initializers is shorter than the number of array elements to be initialized, the remaining elements are initialized to zero If an array is declared without a size and is initialized to a series of values, it is implicitly given the size of the number of initializers.
43
43 Outline One-dimensional arrays The Relationship between Arrays and Pointers Pointer Arithmetic and Element Size Passing Arrays to Functions Two-Dimensional Arrays Multidimensional Arrays Dynamic Memory Allocation
44
44 The relationship between arrays and pointers The array name: an address, or pointer value When an array is declared, the compiler must allocate a base address and a sufficient amount of storage to contain all the elements of the array.
45
45 The relationship between arrays and pointers The array name: an address, or pointer value The array name is the base address of the array the initial location in memory where the array is stored; the address of the first element (index 0) of the array.
46
46 The relationship between arrays and pointers An array name: the base address of the array the initial location in memory where the array is stored; the address of the first element (index 0) of the array. Memory Base address: grade grade[0] grade[1] grade[2] grade[99]
47
47 The relationship between arrays and pointers #define NUM 100 #include int main(void){ int *p, grade[NUM]; p = grade; printf("Value of pointer p: %u\n", p); printf("Value of grade: %u\n", grade); printf("Address of grade[0]:%u\n", &grade[0]); } % a.out Value of pointer p: 4290704864 Value of grade: 4290704864 Address of grade[0]:4290704864
48
48 The relationship between arrays and pointers Difference betw. an array name and a pointer A pointer is a variable that takes addresses as values. The value of a pointer can be changed. An array name is a particular fixed address that can be thought of as a constant pointer. The value of an array name cannot be changed.
49
49 Outline One-dimensional arrays The Relationship between Arrays and Pointers Pointer Arithmetic and Element Size Passing Arrays to Functions Two-Dimensional Arrays Multidimensional Arrays Dynamic Memory Allocation
50
50 Pointer Arithmetic and Element Size Pointer Arithmetic If p is a pointer to a particular type, then the expression p+1 yields the correct machine address for storing or accessing the next variable of that type
51
51 Pointer Arithmetic and Element Size #define NUM 5 #include int main(void){ int *p, grade[NUM]={100,80,90,90,80}; int sum = 0; p = grade; printf("p : %u\n", p); printf("p+1 : %u\n", p+1); printf("*(p+1): %d\n", *(p+1)); } % a.out p : 4290705240 p+1 : 4290705244 *(p+1): 80 If p is a pointer to a particular type, p+1 is the correct machine address for storing or accessing the next variable of that type
52
52 Pointer Arithmetic and Element Size Pointer Arithmetic In a similar fashion, pointer expressions such as p+i and ++p and p+=i all make sense If p is a pointer to a particular type, p+1 is the correct machine address for storing or accessing the next variable of that type
53
53 Pointer Arithmetic and Element Size #define NUM 5 #include int main(void){ int *p, grade[NUM]={90,80,70,60,50}; int sum = 0; p = grade; printf("%d\n", *(p++)); printf("%d\n", *(++p)); printf("%d\n", *(p+=2)); } % a.out 90 70 50
54
54 Pointer Arithmetic and Element Size #define NUM 5 #include int main(void){ int *p, grade[NUM]={100,100,100,100,100}; int sum = 0; for(p=grade; p < &grade[NUM]; ++p) sum += *p; printf("sum = %d\n", sum); return 0; } % a.out sum = 500
55
55 Pointer Arithmetic and Element Size Pointer Arithmetic If p and q are both pointing to elements of an array, then what is the value of (p – q) the int value representing the number of array elements between p and q. If p is a pointer to a particular type, p+1 is the correct machine address for storing or accessing the next variable of that type
56
56 Pointer Arithmetic and Element Size #include int main(void){ double a[2], *p, *q; p = &a[0]; q = p +1; printf("%d\n", q-p); printf("%d\n", (int)q-(int)p); return 0; } % a.out 1 8 Assume a double is stored in 8 bytes. The value printed by the last statement is system-dependent. On many system a double is stored in eight bytes.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.