This chapter delves into the fundamentals of pointers in C programming, exploring their characteristics, operations, and applications. We start with the basic definition of pointers, move on to special types such as constant and variable pointers, and discuss their roles in dynamic memory allocation and function parameters. Additionally, we cover pointers in the context of arrays and strings, providing practical examples to illustrate their functionality. Essential for every C programmer, mastering pointers will enhance your coding efficiency and memory management skills.
An Image/Link below is provided (as is) to download presentation
Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.Content is provided to you AS IS for your information and personal use only.Download presentation by click this link.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.During download, if you can't get a presentation, the file might be deleted by the publisher.
E N D
More Related Content
Presentation Transcript
Chapter 7 Pointers (指针) §7.1 Pointer Basics §7.2 Some Special Pointers §7.3 Pointer in Function §7.4 Pointer and String §7.5 “struct” and Linked List §7.6 Function Pointer
§7.1 Pointer Basics Memory Space • Memory space • A “continuous” space • Three regions • Memory address • Each memory unit has an address • Variable address • The initial address of the memory allocated for the variable int i=0; Code Region Static Region (Static variables, global variables, ...) Dynamic Region (local variables, parameters, ...) Heap ( used by programmer) Stack (used by system)
…… What’s a Pointer? • Pointer: • the variable to hold memory addresses as its value Value Pointed 30606 32820 30 Pointer’s name 30606 ptr Pointer’s addr. Pointer’s value
Declare a Pointer • Pointer is a composite data type • Syntax: dataType * pointerName; • For example, a pointer named pCount that can point to an int value: int *pCount; Pointer type Pointer symbol “*” Pointer name
Initialize a Pointer • Implicit initialization • A local pointer is assigned an arbitrary value • A global pointer is assigned to NULL (pointing nothing) • NULL is in fact “00000000” Not recommended! May cause fatal runtime error or accidental data modification!
Initialize a Pointer • Explicit initialization (recommended) int count=5; int *pCount = &count; int *ptr = NULL; Address-of operator “&”. The value of “&i” is the address of i. TestPointer Run
Indirect Reference • Indirection: referencing a value through a pointer. For example: int count=5; int *pCount = &count; count++; //direct reference (*pCount)++; //indirect reference Indirection operator “*”. The value of “*ptr” is the valued pointed by ptr.
p vs. *p vs. &a int age; int *age_ptr = &age; Then, age_ptr &age *age_ptr age *age_ptr = 50 age = 50; (*age_ptr)++; age++; \ *age_ptr++; *(age_ptr++);
Operations of Pointer • Operations on the address, not the value pointed • Several specific operations • Assignment • Movement • Subtraction • Comparison • The pointer type determines the unit of the operation results For example: p±n;// move n*sizeof( pionter type)
Examples void main() { int a =10, b = 20; int *pa, *pb; pa = &a; //Assign the address directly pb = pa+2; cout <<"a in: "<< &a <<endl; cout <<"b in: "<< &b <<endl; cout <<"pa is: "<< pa <<endl; cout <<"pa points to: "<< *pa <<endl; cout <<"pb is: "<< pb <<endl; cout <<"pb points to: "<< *pb <<endl; if(pa != pb) cout <<"pa and pb are not equal!"<<endl; cout<<"pb - pa is "<<pb-pa<<endl; }
Cautions • The type of the address assigned to a pointer must be consistent with the pointer type. For example, int area = 1; double *pArea = &area; • The white space besides “*” is optional int*ptr; int *ptr; int* ptr; int * ptr; • One “*” for one pointer int *ptr1, *ptr2; //two pointers int* ptr1, ptr2; // one pointer, one integer
§7.2 Some Special Pointers • Constant Pointer (指针常量) • A pointer whose value can not be changed double radius = 5; double * const pValue = &radius; (*pValue) = 3.0; pValue ++; • Pointer of Constant (常量指针) • A pointer that points to a constant double radius = 5; const double * pValue = &radius; (*pValue) = 3.0; raidus = 3.0
Pointer vs. Reference • Reference is alias • No separate memory, address • Bound with the variable • Must be initialized • Pointer is variable • Memory, address (of itself) • Independent of the variable pointed • Can be reassigned different values
Pointer and Array • The name of an array represents the starting address • An array variable is essentially a pointer “myList” &myList[0]
Pointer and Array You can access city or pCity using the array syntax or pointer syntax. For example, char city[5]=“GZ”; char *pCity=city;//char *pCity=&city[0]; cout << city[1] << endl; cout << *(city + 1) << endl; cout << pCity[1] << endl; cout << *(pCity + 1) << endl; Run ArrayPointer Run PointerWithIndex
Pointer and Array • Array variable is different from a pointer • Array name is a constant (not variable) address int array[10]; int*ptr=array; for (k=0; k<5; k++){ cout<< *(ptr++); cout<< *(array++); }
§7.3 Pointer in Function • Pointer as parameter • The address stored in the pointer is passed to the function • A kind of pass-by-reference Run TestPointerArgument void swap(int *p1, int *p2) { int temp; temp = *p1; *p1 = *p2; *p2 = temp; } void swap(int *p1, int *p2) { int *temp; temp = p1; p1 = p2; p2 = temp; }
Pointer as parameter p2, 0028F711 对指针本身来讲,是“值传递”; 对指针指向的目标来讲,是“引用传递”。 0028F820 p1, 0028F51D 0028F814 void myswap(int *p1, int *p2){ int *temp; temp = p1; p1 = p2; p2 = temp; } pt2, 0028F7EC pt1, 0028F808 main(){ int *pt1, *pt2; … myswap(pt1, pt2); … } b, 0028F814 5 a, 0028F820 8 BottomofStack栈底
Pointer as Return Value • The address stored in a pointer is returned int max=0; int *getMax(); void main(){ int *p; p=getMax(); cout<<"Max is “<<*p); } int *getMax(){ int tmp=max, i; for(i=0;i<3;i++){ cout<<"Please enter No. "<<i<<endl; cin>>tmp; if(tmp>max) max=tmp; } return &max; } Don’t return a local pointer! --it becomes invalid after the return! WrongReverse
Dynamic Memory Allocation • The method allowing programmers to allocate storage • Dynamically (during the execution time) and • “Manually” (using explicit statement) • “new” operator: to allocate memory int *pValue = new int; int *mylist = new int[10]; Allocate memory for an int variable; The address is assigned to “pValue”. Allocate memory for an array of 10 int elements; The address is assigned to “mylist”. CorrectReverse
The “delete” Operator • The memory allocated by “new” remains available until • you explicitly free it or • the program terminates. • “delete”: to free memory reserved by “new”. delete pValue; delete [] mylist; • Memory leak • The memory space becomes inaccessible due to the loss of pointing int *p = new int; p = new int; It’s good manner to always explicitly free memory allocated by “new”. (0x00001234) p delete p; (0x00001267)
Case Study: Counting the Occurrences of Each Letter • Generate 100 lowercase letters randomly and assign to an array of characters. • Count the occurrence of each letter in the array. CountLettersInArray Run
§7.4 Pointer and C-string • Two ways to process strings • To treat strings as arrays of characters • known as pointer-based strings or C-strings • To process strings using the string class • The string class will be introduced in Chapter 9
C-string • Two ways to declare C-string • Using an array variable char city[7] = "Dallas"; char city[] = {'D', 'a', 'l', 'l', 'a', 's', '\0' }; char city[] = "Dallas"; cout << city; char city[7]; city= "Dallas";
C-string using Pointer • Declare a string variable using a pointer char *pCity = "Dallas"; cout<<pCity;
Reading Strings • Using “cin”: can’t read in white space char city[10]; cin >>city; • Using “getline” : can read any character. • a function defined in iostream cin.getline(char array[], int size, char delimitChar) char *city2; cin>>city2; No memory is allocated to store the content of city2. Where to store? The last character is reserved for '\0'. Where to stop? delimitChar is read but not stored. Default delimitChar is ‘\n’.
More Declarations struct data { int day, month, year; } ; struct student { char name[20]; long num; struct data birthday; //结构体嵌套 } ; struct student *pst; struct student st[2]; pst = new struct student;
Typedef • to assign alternative names to existing types typedef int km_per_hour ; typedef int points ; km_per_hour current_speed ; points high_score ; ... struct var { int data1; char data2; }; struct var a; typedef struct var newtype; newtype b;
void swapStd(Std st[], int size){ struct student *pst; pst = new struct student; for(int i =1; i<size; i+=2){ strcpy(pst->name,st[i-1].name); pst->num = st[i-1].num; pst->birthday.year = st[i-1].birthday.year; pst->birthday.month = st[i-1].birthday.month; pst->birthday.day = st[i-1].birthday.day; …… } delete pst; } Case study #include <iostream> #include <iomanip> using namespace std; struct data { int day, month, year; }; struct student{ char name[20]; long num; struct data birthday; //结构体嵌套 }; typedef struct student Std; int main(){ Std st[2]; for(int i =0; i<2;i++){ cout<<"Input …:\n"; cin>>st[i].name; cin>>st[i].num; cin>>st[i].birthday.year; … } swapStd(st, 2); cout<<“…\n"; }
Linked List • 链表:a data structure consisting of a group of nodes which together represent a sequence. • 逻辑关系用指针表示。 • 单链表、双向链表和循环链表等。
§7.6 Function Pointer (函数指针) • Entry address of function (入口地址) • Address of the first instruction • Represented by function name • Pointer of function • Pointing to a function • Containing the entry address of the function
Declaration of function pointer • Syntax functionType (*nameOfPointer)(ParameterList) E.g.: • Pointing to functions with matching header: • Same parameter list and return type • E.g. int (*p1)(int); int max(int, int);int min(int,int);int (*p)(int, int); p = max; p = min;
Invocation via function pointer • Similar to invocation via function name • Syntax: (*functionPointer)(acutualParameterList); *functionPointer(acutualParameterList) • 另外一种格式-不推荐 函数指针名(实参表); p =max;c = (*p)(a,b); c = max(a,b);
函数指针示例 void print_stuff(float dtoi){ cout<<"This is the print stuff function.\n“;} void print_message(float ltd){cout<<"The data to be listed is "<<ltd<<endl;} void print_float(float dtp){cout<<"The data to be printed is "<<dtp<<endl;} int main(){ float pi = (float) 3.14159; float two_pi = (float)2.0*pi; void (*function_pointer)(float); function_pointer = print_stuff; *function_pointer(pi); function_pointer = print_message; *function_pointer(two_pi); *function_pointer(13.0); function_pointer = print_float; *function_pointer(pi); return 0; } This is the print stuff function. This is the print stuff function. The data to be listed is 6.28318 The data to be listed is 13 The data to be printed is 3.14159