340 likes | 469 Vues
This guide provides a comprehensive introduction to pointers in C programming. It covers the declaration of pointers, dereferencing, pointer arithmetic, and the relationship between pointers and arrays. Key examples illustrate how to manipulate pointers to access and modify data in memory efficiently. Additionally, it explores null pointers, dynamic memory allocation, and structures containing pointers. Learn how to effectively utilize pointers for improved memory management and flexibility in programming tasks.
E N D
Pointer • To hold the location of another variable • Declaration: • a type and a name with an asterisk • E.g. int *ptr; • Assigning a value • ptr = &k;
More on Pointer int k, j, *ptr; k = 25; j = k; ptr = &k; • Recall: Variable • Name • Value • Memory location: address • Pointer • Record the address of another variable k 2 1335 1336 1337 j ptr 2 1336
Dereferencing • Refer to the value of that which it points to by using the indirection operator * • Called dereferencing operator sometimes • *ptr = 2; • Same as: • k = 2; • Different from • ptr = 2; • Common mistake: forget * when dereferencing
Pointer operation • Commonly used operation • +, - • Note: make sure the pointer is pointing to a valid address • Example • ptr++ • The pointer moves to the next integer value in memory (since ptr is an integer pointer defined before) ptr
Pointer and Array (I) • Consider the following array: • int a[ ] = {1, 2, 3, 4, 5, 6} • Alternatively access them via a pointer as follows: • int *ptr; • ptr = &a[0]; ptr a[0] a[1]
Pointer and Array (II) int a[ ] = {1, 2, 3, 4, 5, 6} int *ptr; ptr = &a[0]; ptr ++; *ptr = 10; ptr a[0] a[1] 10
Example int a[6] = {1, 2, 3, 4, 5, 6}; int *ptr; int sum = 0; for (ptr = &a[0]; ptr <= &a[5]; ptr++) sum += *ptr; for (ptr = a; ptr <= a + 5; ptr++) sum += *ptr;
Example (II) int a[6] = {1, 2, 3, 4, 5, 6}; int *p, *q; int b[6], i; p = a; q = b; for (i = 0; i < 6; i++) *q++ = *p++;
Null pointer • A regular pointer of any pointer type • with a special value NULL (0 in most OS) • Signify that the pointer intentionally does not have a target . • not pointing to any valid reference or memory address. • E.g., ptr = NULL; • Good programming habit: • Set any pointer as NULL initially
string.h • string: an array of characters • Functions in string.h • #include <string.h> char * strcpy (char *s1, const char *s2); • char str[5]; strcpy(str, “abcd”); char * strcat(char *s1, const char *s2); • Concatenate s2 to s1 and return s1. char str1[10] = “abcd”; strcat(str1, “efg”); • Make sure s1 gets enough space
String.h – cont. int strcmp(const char * s1, const char * s2); • How ? • returning negative value if s1<s2, zero if s1 and s2 are identical, positive value if s1>s2 size_t strlen(const char * s) • Returns length of s
Multidimensional Array and Pointers (I) • Pointers can point to multidimensional arrays too • Row major • E.g. char A[3][4] A[0][0] A[0][1] A[0][2] A[0][3] A[1][0] A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3]
p Multidimensional Array and Pointers (II) char * p; p = &A[0][0] • How do we get to A[0][1]? p += 1; • How do we get to A[1][0]? p += 3; • How do we get to A[2][3]; p += 7; or p = &A[2][3]; A[0][0] A[0][1] A[0][2] A[0][3] A[1][0] A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3]
Multidimensional Array and Pointers (III) • For one dimensional array • int a[10], *p; • p = a; • For multidimensional array • int b[10][10], *p; • p = &b[0][0]; • If p = b; • “warning: assignment from incompatible pointer type” • *b is a integer pointer, not b; • Remember: when passing a 2D array to a function, specify the number of columns
Array of Pointers char aname[][15] = { ``no month'', ``jan'', ``feb” }; char *name[] = { ``no month'', ``jan'', ``feb'', ... };
Pointers and Structures • Declaration struct date *datePtr; • Initialization datePtr = &today; • Access members • (*datePtr).year • datePtr->year • struct date{ • int day; • char month[10]; • int year; • }; • struct date today;
Structures contains pointers • Pointers can be members in a structure struct date{ int day; char* month; int year; }; • Special case: struct date{ int day; char* month; int year; struct date *next; };
Linked List • What is a list? • Node • Link • An alternative to Array • Pros/Cons • + More flexible • + Can grow and shrink as necessary • + Insert and delete node with particular index • - Cannot be randomly accessed • + sorted (ordered list) • - non-uniformed find time
Linked List • Operations • Start a list • Create a node • Insert • Search • Query • Print
Dynamically allocate memory • Why • Allocate memory at run-time • Recall variable definition • Pre-claim memory during compiling • Has to prepare for the worst case • Maybe waste of memory space • Dynamically memory allocation apply for memory when needed • Most frequently associated with array, string and struct
Memory Allocation • malloc is by far most frequently used • Defined in <stdlib.h> void *malloc(size_t size); • Allocate memory space with size bytes • Why does it return a void pointer? • Because it doesn't matter to malloc to what type this memory will be used for • If no memory of the size available, will return null • Be sure to check whether it is null;
Example int *ip; ip = malloc(12); if (ip == NULL) { printf("ERROR: Malloc failed"); exit(-1); }
Function sizeof • Helpful when dynamically allocating memory • sizeof(data type) returns a size_t of the data type in byte(s) • For a typical 32-bit machine • sizeof(int) returns 4
Example: malloc array • Difficulty in estimating the proper size of array ahead of time. int *a; a = malloc(n * sizeof(int)); • Can we just say a = malloc(n* 4)? • If success, you got all the space needed • Then you are able to use a[i] or *(a+i) to access the elements
Free Allocated Space • Very important • System won’t automatically take back memory space allocated through malloc • If not free, a memory leak • How? • Use function • void free(void *ptr); • It release the memory space referenced by ptr • Note that free can take in NULL, as specified by ANSI
Build a Linked List • Build a structure representing a node struct studentRecord{ int idNum; struct studentRecord *next; }; • Initialize the node struct studentRecord *first = NULL;
Create a node • Follow these steps: • Allocate memory for the node • Set data into the node struct studentRecord *new_student; new_student = malloc(sizeof(struct studentRecord )); (* new_student).idNum = 1; new_student next = NULL;
Insert a node: insert in the front • Follow these steps: • Create a node • Set the node pointing to the front of the list • Set it as the starting node of this list new_student = malloc(sizeof(struct studentRecord )); new_student idNum = 2; new_student next = first; first = new_student ;
Insert a node: insert in middle • To insert a new node after node called pt, follow these steps: • Create a node • Set the node pointing to the next node after pt in the list • Set it as the next node of this list after pt new_student = malloc(sizeof(struct studentRecord )); new_student idNum = 2; new_student next = pt next; pt next = new_student ;
Traversing along the List for (p = first; p != NULL; p = pnext) { …. } int Length(struct studentRecord* first) { int count = 0; struct studentRecord* current = first; while (current != NULL) { count++; current=current->next; } return(count); }
Get nth Element in List int GetNth(struct studentRecord * first, int index) { struct studentRecord * current = first; int count = 0; // the index of the node while (current != NULL) { if (count == index) return(current idNum ); count++; current = current next; } return(-1); // if we get to this line, the caller was asking // for a non-existent element }
Delete • Delete (almost reverse of insertion) • locating the node to be deleted (see search a linked list) • altering the previous node to bypass the deleted node • calling free to reclaim the space occupied by the deleted node
Example for deleting • To delete a node p from a linked list, you should also know the node which is right ahead of p in the list if (p != NULL) { q next = p next; free(p); } • If deleting the first node in the list if( p == first ) { first = p->next; free(p); }