html5-img
1 / 33

Pointer

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

hamal
Download Presentation

Pointer

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

Presentation Transcript


  1. 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;

  2. 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

  3. 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

  4. 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

  5. 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]

  6. 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

  7. 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;

  8. 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++;

  9. 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

  10. 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

  11. 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

  12. 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]

  13. 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]

  14. 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

  15. Array of Pointers char aname[][15] = { ``no month'', ``jan'', ``feb” }; char *name[] = { ``no month'', ``jan'', ``feb'', ... };

  16. 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;

  17. 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; };

  18. 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

  19. Linked List • Operations • Start a list • Create a node • Insert • Search • Query • Print

  20. 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

  21. 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;

  22. Example int *ip; ip = malloc(12); if (ip == NULL) { printf("ERROR: Malloc failed"); exit(-1); }

  23. 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

  24. 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

  25. 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

  26. Build a Linked List • Build a structure representing a node struct studentRecord{ int idNum; struct studentRecord *next; }; • Initialize the node struct studentRecord *first = NULL;

  27. 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;

  28. 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 ;

  29. 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 ;

  30. Traversing along the List for (p = first; p != NULL; p = pnext) { …. } int Length(struct studentRecord* first) { int count = 0; struct studentRecord* current = first; while (current != NULL) { count++; current=current->next; } return(count); }

  31. 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 }

  32. 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

  33. 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); }

More Related