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.

Slides:



Advertisements
Similar presentations
SEE C GO Provisional Title. Syntax Types int, float, double, char, void Identifiers foo Operators + - * / ^ Delimiters ; {} () “” ‘’ Keywords return,
Advertisements

Dynamic memory allocation
An introduction to pointers in c
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.
Pointers in C Rohit Khokher
Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
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.
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.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Programming Assignment 8 CS113 Spring Programming Assignment 8 Implement the sorting routine of your choice. Compare average performance of your.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Pointers Applications
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C Tokens Identifiers Keywords Constants Operators Special symbols.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
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.
7. Pointers, Dynamic Memory 20 th September IIT Kanpur 1C Course, Programming club, Fall 2008.
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.
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
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.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
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.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
POINTERS.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
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.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Structures CSE 2031 Fall March Basics of Structures (6.1) struct point { int x; int y; }; keyword struct introduces a structure declaration.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Pointers. Pointer Fundamentals  When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable. –int.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Generic Programming in C
Stack and Heap Memory Stack resident variables include:
C Primer.
Lecture 6 C++ Programming
Some examples.
Object Oriented Programming COP3330 / CGS5409
Memory Allocation CS 217.
Outline Defining and using Pointers Operations on pointers
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Structures CSE 2031 Fall February 2019.
Structures CSE 2031 Fall April 2019.
Structures CSE 2031 Fall May 2019.
Structures EECS July 2019.
15213 C Primer 17 September 2002.
Pointers.
Presentation transcript:

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 another pointer pointing to it. int x; int * px; int ** ppx; ppx = &px; px = &x; /* i.e. *ppx = &x */ **ppx = 10; /* i.e. *px =10; i.e. x=10; */ ppx = (int **) malloc(sizeof(int *)); **ppx = 20; /* Wrong, since *ppx is uninitialized! */

Arrays of Pointers (1) u If we have an array of structures, each structure can potentially be very big. u To sort such an array, a lot of memory copying and movements are necessary, which can be expensive. u For efficiency, we can use array of pointers instead: struct book{ float price; char abstract[5000]; }; struct book book_ary[1000]; struct book * pbook_ary[1000]; …… for(i=0;i<1000;i++) pbook_ary[i] = &book_ary[i];

Arrays of Pointers (2) void my_sort(struct book * pbook_ary[ ], int size) { int i, j; struct book *p; for(i=1;i<size;i++){ p=pbook_ary[i]; for(j=i-1;j>=0;j--) if(pbook_ary[ j ] -> price > p -> price) pbook_ary[ j+1 ]= pbook_ary[ j ]; else break; pbook_ary[ j+1 ] = p; }

Arrays of Pointers (3) struct book ** search_range(struct book * pbook_ary[ ], int size, float low, float high, int *num) { int i, j; for(i=0;i<size;i++) if(pbook_ary[i] -> price >= low) break; for( j=size; j>0;j--) if(pbook_ary[ j] -> price <= high) break; /* i, i+1, …, j are the elements in the range */ *num = j – i + 1; return &pbook_ary[ i ]; }

Dynamic Two Dimensional Arrays int ** ary; int m, n; srand( time(NULL) ); m = rand( ) % ; ary = (int **) malloc( m * sizeof(int *) ); for( j =0; j< m; j++){ ary[ j ]= (int *) malloc ( (j+1) *sizeof(int)); } ary[3][4] = 6; *( *( ary + 3) + 4) = 6; ary->[3]->[4] = 6; /* NO! You can not do this */

const Pointers (1) u The const keyword has a different meaning when applied to pointers. void test( const int k, const int * m) { k ++; /* 1 */ (*m) ++; /* 2 */ m ++; /* 3 */ printf("%d,%d", k, *m); } u The compiler will warn you about the 1 st and 2 nd increments, but not the 3 rd.

const Pointers (2) u The reason we use const before parameters is to indicate that we will not modify the value of the corresponding parameter inside the function. u For example: we would not worry about the format_str is going to be modified by printf when we look at its prototype: –int printf(const char * format_str, ……);

Pointers to Functions (1) u Since a pointer merely contains an address, it can point to anything. u A function also has an address -- it must be loaded in to memory somewhere to be executed. u So, we can also point a pointer to a function. int (*compare)(int, int); 1. Compare is a pointer 2. To a function 3. That returns an int value 1 2 3

Pointers to Functions (2) typedef struct{ float price; char title[100]; } book; int (*ptr_comp)(const book *, const book *); /* compare with int * ptr_comp(const book *, const book *); */ u Do not forget to initialize the pointer -- point the pointer to a real function!

Pointers to Functions (3) #include int compare_price(const book * p, const book *q) { return p->price-q->price; } int compare_title(const book * p, const book *q) { return strcmp(p->title,q-> title); } int main( ){ book a, b; a.price=19.99; strcpy(a.title, "unix"); b.price=20.00; strcpy(b.title, "c"); ptr_comp = compare_price; printf("%d", ptr_comp(&a, &b)); ptr_comp = compare_title; printf("%d", ptr_comp(&a, &b)); return 0; }

Example: The qsort() Function (1) u Often, you want to sort something using the quick sort algorithm. C provides a qsort() function in its standard library. Here is the prototype: SYNOPSIS #include void qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *) ); u The base argument points to the element at the base of the array to sort. u The nel argument is the number of elements in the table. The width argument specifies the size of each element in bytes. u The compar argument is a pointer to the comparison function, which is called with two arguments that point to the elements being compared.

Example: The qsort() Function (2) u An example: #include …… { book my_books[1000]; …… qsort(my_books, 1000, sizeof(book), compare_price); …… qsort(my_books, 1000, sizeof(book), compare_title); …… }

Deallocating Dynamic Structures u For every call to malloc used to build a dynamically allocated structure, there should be a corresponding call to free. u A table inside malloc and free keeps track of the starting addresses of all allocated blocks from the heap, along with their sizes. u When an address is passed to free, it is looked up in the table, and the correct amount of space is deallocated. u You cannot deallocate just part of a string or any other allocated block!

Example #include int main(){ char *p = malloc(100); free(p+1); printf("Finsished!\n"); return 0; }