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.

Slides:



Advertisements
Similar presentations
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Advertisements

Dynamic memory allocation
C Language.
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.
Programming and Data Structure
Structure.
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.
Structures in C.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
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.
Kernighan/Ritchie: Kelley/Pohl:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Structures. An array allows us to store a collection of variables However, the variables must be of the same type to be stored in an array E.g. if we.
Informática II Prof. Dr. Gustavo Patiño MJ
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
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.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Learners Support Publications Classes and Objects.
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.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Object-Oriented Programming in C++
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
Welcome to Concepts of Pointers. Prepared by:- Sumit Kumar PGT(Computer Science) Kv,Samba.
Review 1 List Data Structure List operations List Implementation Array Linked List.
CPS120: Introduction to Computer Science Lecture 15A Structures.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
The const Keyword Extreme Encapsulation. Humble Beginnings There are often cases in coding where it is helpful to use a const variable in a method or.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
Computer science C programming language lesson 3.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
User-Written Functions
Pointers and Pointer-Based Strings
Pointers and References
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Classes and Objects.
Pointers and Pointer-Based Strings
Submitted By : Veenu Saini Lecturer (IT)
Pointers and References
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

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 previously in the context of passing the address of a struct as a function argument in order to allow the function to change the values of the members of the struct. Sometimes we wish to pass a pointer to a struct as a function argument even though we do not wish to change the values of any of its members. This need may arise because of the large overhead involved in "bodily" copying the values of all of the members of the struct. It may be much more efficient to pass the address of the struct and to de-reference the pointer within the function, using the usual indirection operator *.

3 As an example, consider a variation on the function show_details(). We had specified the type PERSON, using the following typedef:- typedef struct { int age; float weight; } PERSON; And the original version of show_details() was:- void show_details( PERSON who ) { printf( "Person's age was: %d\n", who.age ); printf( " sex was: %c\n", who.sex ); who.weight = who.weight * 2.2;/* Kg -> lb */ printf( " weight (lb) was: %5.1f\n", who.weight ); }

4 Let us define a new function s2_details() which takes an argument of type PERSON * - the address of a PERSON. void s2_details( PERSON * pWho ) { printf( "Person's age was: %d\n", (*pWho).age ); printf( " sex was: %c\n", (*pWho).sex ); /* Kg -> lb */ (*pWho).weight = (*pWho).weight * 2.2; printf( " weight (lb) was: %5.1f\n", (*pWho).weight ); } pWho holds the address of a whole struct, *pWho denotes the struct itself, and (*pWho).age denotes one of its members. So s2_details() can access all the members of a PERSON without having to copy the whole struct.

5 The Arrow Operator -> C provides a more friendly syntax for accessing the members of a structure from a pointer, using the -> operator. For example, pWho->age is the same as (*pWho).age. (In general, the -> operator returns the member named on the right of -> from the structure pointed to by the pointer on the left.) So we could simplify the assignment statement within s2_details() as follows

6 (*pWho).weight = (*pWho).weight * 2.2; would become pWho->weight = pWho->weight * 2.2;

7 Pointers to Constants (ANSI only) The problem with passing a pointer as a function argument is that the function has total freedom to change the object pointed at. In the above example, the programmer has needlessly changed the value of the.weight member. Instead of just displaying a weight, the function changes its value. There is one safeguard which can allow a programmer to pass a pointer to a function knowing that the function will not be allowed to alter it - declare the argument as constant, using the const keyword. In the new definition of s2_details(), below, pWho is declared as a pointer to a const PERSON. Any statement which attempted to change the value of the structure pointed at by pWho would be flagged as a compilation error.

8 void s2_details( const PERSON * pWho ) { printf( "Person's age was: %d\n", pWho->age ); printf( " sex was: %c\n", pWho->sex ); printf( " weight (lb) was: %5.1f\n", pWho->weight * 2.2 ); } Note that we have eliminated the assignment statement pWho->weight = pWho->weight * 2.2; and replaced it by using the expression pWho->weight * 2.2 inside the printf() statement.

9 Dynamic Memory Allocation - the Heap C provides a managed area of storage known as the heap which is available to the programmer for the creation of data objects of any size while the program is actually executing. Why would we wish to use the heap? We have seen that one problem with arrays is that the dimension must be declared at compile time:  to be on the safe side, the programmer must make the array large enough for any conceivable case.  Another problem with arrays is the very simplicity of their structure. There are some data structures, e.g. trees, which do not naturally fit into a uniform collection of adjacent elements each of the same size.  A further problem with arrays is that the addresses of all their elements are fixed. Some data objects have a tendency frequently to change their structure as a program executes: if such an object is stored in an array then there will be much copying of elements to fill up the "holes" which appear.

10 There are two standard library functions malloc() and free() which allow the programmer to claim space from the heap and, subsequently, to release it. The prototypes for these functions are in the include file stdlib.h. malloc() needs to know how much space is required. It locates that amount of space within the heap, marks it as "in use" and returns a pointer to it. For example, malloc( sizeof( float ) ) would claim space on the heap to store one float. In order to access this float we need to have declared a pointer ( a float * ) which will hold its address

11 #include #include void main() { float * pZ; pZ = malloc( sizeof( float ) ); *pZ = 12.3; printf( "Address is %u and contents are %f\n", pZ, *pZ ); } In practice if we wished to store a value of type float then we would simply declare a float variable. We are more likely to use the heap if we wish to store an unknown number of structured types. For example to store a PERSON we could have PERSON * pWho = malloc( sizeof( PERSON ) ); Here we have declared pWho as a pointer to PERSON and we have also initialised it by a call of malloc(). The storage pointed to by pWho could be written to by assignment statements such as /* or (*pWho).age = 40 */ pWho->age = 40; pWho->sex = 'M'; pWho->weight = 75.2;