Pointers Applications

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
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.
1 Objectives ❏ To understand the relationship between arrays and pointers ❏ To understand the design and concepts behind pointer arithmetic ❏ To write.
Engineering Problem Solving with C Fundamental Concepts Chapter 6 Pointers.
Kernighan/Ritchie: Kelley/Pohl:
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
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:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
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.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Pointers Pointer - A pointer is a derived data type; that is it is a data type built from one of the standard types. Its value is any of the addresses.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
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.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the concept and use of pointers ❏ To be able to declare, define,
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the relationship between arrays and pointers ❏ To understand the.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Dynamic Allocation in C
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation
Dynamic Memory Allocation
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Objectives You should be able to describe: Addresses and Pointers
Data Structures and Algorithms Introduction to Pointers
Chapter 10-1: Dynamic Memory Allocation
Pointers and pointer applications
Presentation transcript:

Pointers Applications The void Pointer - With one exception, it is invalid to assign a pointer of one type to a pointer of another type. This is true even though the values in both cases are memory addresses and would therefore seem to be fully compatible. Although the addresses may be compatible because they are drawn from the same set, what is not compatible in the underlying data type of the referenced object. C doesn’t let us use the assignment operator with pointers of different types; is we try to , we get a compile error. The exception to the rule is the void pointer. The void pointer can be used with any pointer and any pointer can be assigned to a void pointer. A void pointer cannot be dereferenced. Example: void *pVoid ; Arrays and pointers - There is a very close relationship between arrays and pointers. The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot be changed. Since the array name is a pointer constant to the first element, the address of the first element and name of the array both represent the same location in memory. We can, therefore, use the array name anywhere we can use a pointer, as long as you do not try to change it’s value. If we have the following declaration: int x[ 5 ] ; the following two expressions result in the same value x &x[0] Also dereferencing the array name gives the same value as a reference to the first element of the array: *x x[0] same same

Pointers Applications Arrays and pointers (continued) - Since the name of the array is a pointer value we can assign this value to other pointer variables of the same type and then use the pointer the same way we use the array name. int main(void) { int a[ 5 ] = {2, 4, 6, 8, 22}; int *p = a; int i = 0; printf(“%d %d\n”, a[i], *p) return 0; } Main function memory space Addresses a[0] 2 48682 a[1] 4 48686 a[2] 6 48690 a[3] 8 48694 a[4] 22 48698 Even though p is a pointer variable, we can use it as an array name 2 2 int main(void) { int a[ 5 ] = {2, 4, 6, 8, 22}; int *p; p = &a[1]; printf(“%d %d\n”, a[0], p[-1]); printf(“%d %d\n”, a[1], p[0]); return 0; } 2 2 4 4

Pointers Applications Pointer arithmetic and arrays - Besides indexing, there is another powerful method of moving through an array: Pointer arithmetic. Pointer arithmetic offers a restricted set of arithmetic operators for manipulating the addresses in pointers. It is especially powerful when we need to move through an array from element to element, such as when we are searching an array sequentially. If we have an array, a, then a is a constant pointing to the first element and a + 1 is a constant to the second element. If we have a pointer, p, pointing to the second element of an array , then p - 1 is a pointer to the previous (first)element and p + 1 is a pointer to the next (third) element. Furthermore, given a, a + 2 is the address two elements from a and a + 3 is the address three elements from a. Given pointer, p, p  n is a pointer to the value n elements away. memory Addresses a a[0] 2 48682 p - 1 a + 1 a[1] 4 48686 p a + 2 a[2] 6 48690 p + 1 a + 3 a[3] 8 48694 p + 2 a + 4 a[4] 22 48698 p + 3 The meaning of adding or subtracting here is different from normal arithmetic. When you add an integer n to a pointer value, you will get a value that corresponds to another index location, n elements away. In other words, n is an offset from the original pointer. To determine the new value, C must know the size of one element. The size of the element is determined by the type of the pointer. This is one of the prime reasons why pointers of different types cannot be assigned to each other.

Pointers Applications Pointer arithmetic allows us to assign an address of an array element to a pointer using the name of the array and the offset. p = a + 1; Second, we can use it with the indirection operator to access or change the value of the element we are pointing to. The two following expressions are exactly the same when a is the name of an array and n is an integer. *(a + n) is identical to a[n] memory Addresses *(a + 0) or a[0] 2 48682 *(a + 1) or a[1] 4 48686 *(a + 2) or a[2] 6 48690 *(a + 3) or a[3] 8 48694 *(a + 4) or a[4] 22 48698

Pointers Applications Pointers and other Operators - Arithmetic operations involving pointers are very limited: Addition can be used when one operand is a pointer and the other is an integer. Subtraction can be used only when both operands are pointers or when the first operand is a pointer and the second operand is an integer. You can manipulate a pointer with the postfix and prefix unary increment and decrement operators. All the following pointer arithmetic operations are valid : p + 5 5 + p p - 5 p1 - p2 p++ --p When a pointer is subtracted from another the result is an index representing the number of elements between the two pointers. The relational operators are allowed only if both operands are pointers of the same type. p1 >= p2 p1 != p2 Pointers and Two-Dimensional Arrays - Just like a single dimensional array the name of a two dimensional array is a pointer constant ( address ) to the first element of the array. In this case, however, the first element is another array. When we dereference the array name, we don’t get the value of the first element, we get the address of the first array (first row) in our two dimensional array. In other words, the dereference of the array name of a two-dimensional array is a pointer to a one-dimensional array. Therefore if we have a two dimensional array: int table [3] [4] the expression table[0] will refer to the first array in our two dimensional array

Pointers Applications Memory Allocation Functions - Modern languages such as C have a feature known as dynamic memory allocation. Dynamic memory allocation uses predefined functions to allocate and release memory for data while the program is running. This effectively postpones the data definition to run time. To use dynamic memory allocation, the programmer must use either standard data types or already must have declared any derived types. Conceptually, we can say that memory is divided into program memory and data memory. Program memory consists of the memory used for main and all called functions. Data memory consists of definitions, such as global data and constants, local definitions, and dynamic data memory. It is also possible for more than one version of the function to be active at a time. In this case, multiple copies of the local variables will be allocated, although only one copy of the function is present. The memory facility for these capabilities is known as the stack. main called and standard functions PROGRAM MEMORY global program heap system stack DATA MEMORY MEMORY

Pointers Applications Memory Allocation Functions (continued) - The heap is unused memory allocated to the program and available to be assigned during its execution. It is the memory pool from which memory is allocated when requested by the memory allocation functions. Four memory management functions are used with dynamic memory. Three of them, malloc, calloc, and realloc, are used for memory allocation. The fourth, free is used to return memory when it is no longer needed. malloc - allocates a block of memory that contains the number of bytes specified in its parameter. It returns a void pointer to the first byte of the allocated memory. The allocated memory is not initialized. The prototype for malloc is as follows: void *malloc( size_t size) ; The size_t type is defined in several header files including <stdio.h>. To provide portability, the size specification in malloc’s actual parameter is generally computed using the sizeof operator. pInt = ( int *) malloc ( sizeof (int) ); If malloc is not successful, it returns a NULL pointer. if( ! (ptr = (int *) malloc ( sizeof (int ) ) ) ) exit(100); calloc - this function is used to allocate memory for arrays. It allocates a contiguous block of memory large enough to contain an array of elements of a specified size. It returns a pointer to the first element of the allocated array. calloc also sets the memory allocated to zero. void * calloc ( size_t element-count, size_t element_size);

Pointers Applications Memory Allocation Functions (continued) - free - When memory locations allocated by malloc, calloc, or realloc are no longer needed, they should be freed using the predefined function free. void free ( void *ptr ); You should free memory whenever it is no longer needed. It is not necessary, however, to clear memory at the end of the program. The operating system will release all memory when your program terminates. It is a logic error to use the pointer after memory has been released.