Advanced Pointer Topics

Similar documents
Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Understanding Pointers

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

CS24 Week 2 Lecture 1

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Dynamic memory allocation

Intermediate Programming, Spring 2017*

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Heap Arrays. Steven R. Bagley

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

EL2310 Scientific Programming

ECE 2400 Computer Systems Programming Fall 2018 Topic 6: C Dynamic Allocation

Dynamic memory. EECS 211 Winter 2019

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Heap Arrays and Linked Lists. Steven R. Bagley


Here's how you declare a function that returns a pointer to a character:

Character Strings. String-copy Example

JTSK Programming in C II C-Lab II. Lecture 3 & 4

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

ME964 High Performance Computing for Engineering Applications

Class Information ANNOUCEMENTS

Fundamental of Programming (C)

Memory Allocation. General Questions

ECE 15B COMPUTER ORGANIZATION

Dynamic Data Structures. CSCI 112: Programming in C

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Subject: Fundamental of Computer Programming 2068

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

CS300 Final Review Questions 1

C Programming Basics II

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

PRINCIPLES OF OPERATING SYSTEMS

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Programs in memory. The layout of memory is roughly:

Linked data structures. EECS 211 Winter 2019

Assist. Prof. Dr. Caner ÖZCAN

CS201 Some Important Definitions

This is CS50. Harvard University Fall Quiz 0 Answer Key

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

CSCI 171 Chapter Outlines

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

PDS Class Test 2. Room Sections No of students

CS61, Fall 2012 Section 2 Notes

High Performance Programming Programming in C part 1

Lecture 8 Dynamic Memory Allocation

Dynamic Memory Allocation

CSC 1600 Memory Layout for Unix Processes"

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Compiling and Running a C Program in Unix

C for C++ Programmers

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

C Programming Language

Warmup January 9th, What is the value of the following C expression? 8*9 % 10/ 2

o Code, executable, and process o Main memory vs. virtual memory

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

CS61C : Machine Structures

Final Intro to C Review

Content. In this chapter, you will learn:

Welcome! COMP s1. Programming Fundamentals

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

Oregon State University School of Electrical Engineering and Computer Science. CS 261 Recitation 2. Spring 2016

211: Computer Architecture Summer 2016

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

SYSC 2006 C Winter 2012

EL2310 Scientific Programming

C mini reference. 5 Binary numbers 12

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

Outline. Briefly review the last class Pointers and Structs Memory allocation Linked lists

Arrays and Memory Management

CS 314 Principles of Programming Languages. Lecture 11

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

Procedural programming with C

CS 610: Intermediate Programming: C/C++ Making Programs General An Introduction to Linked Lists

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Reminder: compiling & linking

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

CS201- Introduction to Programming Current Quizzes

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

Dynamic Memory CMSC 104 Spring 2014, Section 02, Lecture 24 Jason Tang

Dynamically Allocated Memory in C

The University of Calgary. ENCM 339 Programming Fundamentals Fall 2016

Programming in C. 4. Misc. Library Features, Gotchas, Hints and Tips. Dr. Neel Krishnaswami University of Cambridge

ECE/ME/EMA/CS 759 High Performance Computing for Engineering Applications

Section Notes - Week 1 (9/17)

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Transcription:

Advanced Pointer Topics

Pointers to Pointers 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) If we have an array of structures, each structure can potentially be very big. To sort such an array, a lot of memory copying and movements are necessary, which can be expensive. 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( ) % 5000 +10; 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) 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); The compiler will warn you about the 1 st and 2 nd increments, but not the 3 rd.

const Pointers (2) The reason we use const before parameters is to indicate that we will not modify the value of the corresponding parameter inside the function. 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) Since a pointer merely contains an address, it can point to anything. A function also has an address -- it must be loaded in to memory somewhere to be executed. So, we can also point a pointer to a function. int (*compare)(int, int); 1 3 2 1. Compare is a pointer 2. To a function 3. That returns an int value

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

Pointers to Functions (3) #include <string.h> 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) 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 <stdlib.h> void qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *) ); The base argument points to the element at the base of the array to sort. The nel argument is the number of elements in the table. The width argument specifies the size of each element in bytes. 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) An example: #include <stdlib.h> { book my_books[1000]; qsort(my_books, 1000, sizeof(book), compare_price); qsort(my_books, 1000, sizeof(book), compare_title);

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

Example #include <stdio.h> int main(){ char *p = malloc(100); free(p+1); printf("finsished!\n"); return 0;