17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Dynamic memory allocation
Programming Languages and Paradigms The C Programming Language.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
Engineering Problem Solving with C Fundamental Concepts Chapter 6 Pointers.
C Programming : Dynamic memory allocation & Structures 2008/11/19 Made by Jimin Hwa Edited and presented by Souneil Park
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
CS100A, Fall 1997, Lecture 241 CS100A, Fall 1997 Lecture 24, Tuesday 25 November (There were no written notes for lecture 23 on Nov. 20.) Data Structures.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Pointers Applications
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
CGS 3460 Pointer n To hold the location of another variable n Declaration: la type and a name with an asterisk lE.g. int *ptr; n Assigning a value lptr.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Introduction to Data Structures Systems Programming.
Chapter 14 Dynamic Data Structures Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Pointers OVERVIEW.
Chapter 11: Pointers Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 11 Pointers.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Introduction to Data Structures Systems Programming Concepts.
Linked Lists EENG 212 ALGORITHMS And DATA STRUCTURES.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
ECE Application Programming
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Generic Programming in C
Stack and Heap Memory Stack resident variables include:
Chapter 12 – Data Structures
5.13 Recursion Recursive functions Functions that call themselves
12 C Data Structures.
Introduction to Data Structures
Arrays & Dynamic Memory Allocation
CSC215 Lecture Memory Management.
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Review & Lab assignments
CS111 Computer Programming
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Dynamic Memory – A Review
Pointers.
Module 13 Dynamic Memory.
Presentation transcript:

17. ADVANCED USES OF POINTERS

Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed during program execution. Dynamically allocated storage may be used for any kind of data object. The objects most commonly allocated are: Arrays Strings Structures Dynamically allocated structures can be linked together to form lists, trees, and other data structures.

The malloc Function The most important storage allocation function is named malloc. When called, malloc allocates a block of size bytes and returns a pointer to it: void *malloc(size_t size); malloc returns a “generic” pointer that is capable of pointing at an object of any type. malloc’s return value can be stored in a variable of any pointer type: int *pi; pi = malloc(sizeof(int)); /* allocate memory for an int */ For portability, it is best to use sizeof when calling malloc. Memory allocated by malloc is not cleared.

The Null Pointer When malloc cannot locate a memory block of the requested size, it returns a null pointer. The macro NULL represents the null pointer. It is defined in,,,,, and ; one of these must be included in any program that uses NULL. NULL actually stands for the value 0: #define NULL 0 To avoid confusion with the integer 0, it’s usually best to use NULL instead of 0 to represent the null pointer.

The Null Pointer Since NULL is equivalent to 0, it tests false in if, while, do, and for statements: int *p; … if (p) … /* true if p is not NULL */ It is illegal to apply the indirection operator to a null pointer: p = NULL; i = *p; /* illegal */

Dynamically Allocated Strings malloc is often used to dynamically allocate space for strings. malloc is especially useful to allocate space for the result of a string operation: char *result; result = malloc(strlen(s1) + strlen(s2) + 1); strcpy(result, s1); strcat(result, s2); Warning: When using malloc to allocate space for a string, don’t forget to include room for the null character.

Dynamically Allocated Arrays An array can be dynamically allocated by a call of the calloc function.calloc is similar to malloc, but allocates space for an array with nmemb elements, each of which is size bytes long: void *calloc(size_t nmemb, size_t size); The block of memory allocated by calloc is cleared (set to 0 bits).

Dynamically Allocated Arrays Example: int *a, size, i; printf("Enter array size: "); scanf("%d", &size); a = calloc(size, sizeof(int)); printf("Enter array elements: "); for (i = 0; i < size; i++) scanf("%d", &a[i]); Warning: A program that uses malloc or calloc must include the following header file: #include If this file is not included, calloc and malloc would be assumed to return int values, causing unpredictable effects.

The free Function When a block of memory obtained by calling malloc or calloc is no longer referenced by a pointer, it is said to be garbage. In the following example, the memory pointed to by p becomes garbage when p is assigned a new value: int *p, *q; p = malloc(sizeof(int)); q = malloc(sizeof(int)); p = q; Garbage should be avoided; we need to “recycle” memory instead.

The free Function When a block of memory is no longer needed, it can be released by calling the free function: int *p, *q; p = malloc(sizeof(int)); q = malloc(sizeof(int)); free(p); p = q; Warning: Watch for “dangling pointers” left behind by a call of free: int *p, *q; p = malloc(sizeof(int)); q = p; free(p); *q = 0; /* error */

Linked Lists Dynamic storage allocation is useful for building lists, trees, graphs, and other linked structures. A linked structure consists of a collection of nodes. Each node contains one or more pointers to other nodes. In C, a node is represented by a structure. The simplest linked structure is the linked list, which consists of a chain of nodes, with each node pointing to the next node in the chain. A node in a linked list might have the following definition: struct node { int data; struct node *next; }; The use of a structure tag is mandatory, since the node structure contains a reference to itself.

Linked Lists An ordinary pointer variable points to the first node in the list; to indicate that the list is empty, the variable can be assigned NULL: struct node *first = NULL;

The Right Arrow Operator Nodes can be created by calling malloc: struct node *temp; temp = malloc(sizeof(struct node)); The. operator can be used to select the data member in the node that temp points to: (*temp).data = n; Because pointers often point to structures, C provides a special notation (the right arrow selection operator) for selecting members of these structures: temp->data = n;

Example: Inserting into a Linked List The following statements will create a node containing n, then insert it at the beginning of the list pointed to by first: struct node *temp; temp = malloc(sizeof(struct node)); temp->data = n; temp->next = first; first = temp;

Example: Inserting into a Linked List The following example creates a linked list containing numbers entered by the user: struct node *first = NULL, *temp; int n; printf("Enter a series of numbers (enter 0 to stop): "); scanf("%d", &n); while (n != 0) { temp = malloc(sizeof(struct node)); temp->data = n; temp->next = first; first = temp; scanf("%d", &n); } The numbers will appear in the list in the reverse of the order in which they were entered.

Example: Searching a Linked List The following statement searches a list for an integer n: for (temp = first; temp != NULL; temp = temp->next) if (temp->data == n) … /* found n */

Example: Deleting from a Linked List The following statements will delete the first node containing n from the list pointed to by first, assuming that n is present in the list: struct node *p, *q; for (p = first, q = NULL; p != NULL && p->data != n; q = p, p = p->next); if (q == NULL) first = first->next; /* n is at the beginning */ else q->next = p->next; /* n is not at the beginning */ free(p);

Functions Passed as Arguments C does not allow a function to be passed as an argument to another function. However, a pointer to a function can be passed: int find_zero(int (*f)(int)); int poly(int i); int main(void) { printf("Answer: %d\n", find_zero(poly)); return 0; } int find_zero(int (*f)(int)) { int n = 0; while ((*f)(n)) n++; /* or while (f(n)) n++; */ return n; } int poly(int i) { return i * i + i - 12; }

Functions Passed as Arguments Pointers to functions can be used in numerous other ways. For example: A function can return a pointer to a function. A variable can store a pointer to a function. An array may contain pointers to functions.

The qsort Function Certain functions in the C standard library require a function pointer as a parameter. One of the most commonly used is qsort, a general- purpose algorithm capable of sorting any array. The following declaration for qsort appears in : void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); base is a pointer to the first element in the array. nmemb is the number of elements in the array. size is the size of each array element. compar is a pointer to a function that compares two array elements.

The qsort Function When given two pointers p and q to array elements, compar must return a number that is Negative if *p is “less than” *q. Zero if *p is “equal to” *q. Positive if *p is “greater than” *q.