Pointers 2 COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.

Slides:



Advertisements
Similar presentations
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Advertisements

SEE C GO Provisional Title. Syntax Types int, float, double, char, void Identifiers foo Operators + - * / ^ Delimiters ; {} () “” ‘’ Keywords return,
An introduction to pointers in c
CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
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.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
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.
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:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
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.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
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.
Linked Lists Chained nodes of information create what are called linked lists, with each node providing a link to the next node. A useful feature of linked.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
Pointers Applications
Arrays and Pointers in C Alan L. Cox
COP 3275 COMPUTER PROGRAMMING USING C Instructor: Diego Rivera-Gutierrez
The preprocessor and the compilation process COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a ‘wrappered function’? –What is a clean interface? –How to earn your.
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
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.
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.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1!  And before that…  Review!  And before that…  Arrays and strings.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
Pointers OVERVIEW.
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.
Dynamic memory allocation and Pointers Lecture 4.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
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 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
COP Structures Instructor: Diego Rivera-Gutierrez I’m back baby!
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Suppose we defined the data type: struct custrec.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 3 – August 28, 2001.
Homework due Test the random number generator Create a 1D array of n ints Fill the array with random numbers between 0 and 100 Compute and report the average.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
1 CSC103: Introduction to Computer and Programming Lecture No 24.
Pointers COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Arrays as pointers and other stuff COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
COP 3275 – Character Strings Instructor: Diego Rivera-Gutierrez.
COP 3275 – Character Strings and Introduction to Pointers Instructor: Diego Rivera-Gutierrez.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
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.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
EGR 2261 Unit 11 Pointers and Dynamic Variables
CSCI206 - Computer Organization & Programming
Dynamic Memory Allocation
Clear1 and Clear2 clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) {
Circular Buffers, Linked Lists
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
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.
Arrays as pointers and other stuff
Presentation transcript:

Pointers 2 COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ

Administrative stuff Quiz on Friday Easy question on pointers (regarding basic operators + malloc) (15 pts) Create one function that does an operation to the list we will create today (15 pts) String function (15 pts) Free credit question. (Every answer is correct for this one – 5pts) Homework #5 will be posted tonight.

Homework #5 Allow different sizes of boards! Move seed, # of mines and board size to console arguments. -s for seed -m for mines -r for rows -c for columns Include mine counter (#mines – mines assigned) Winning condition – including when all unopened tiles are mines Due on July 24 th.

Let’s build a better list… We have a struct that saves all the info for a student (name, UFID, DOB, major, year, etc). struct student{ char *name; int UFID; char major[3]; struct Date DOB; int year; };

Let’s build a better list… For simplicity let’s only use name struct student{ char *name; struct student *next; };

Remember what we are after: AnaAndrewCristinaJulianaMichael

On Monday – Creation of the list struct student ana; ana.name = "Ana"; struct student andrew; andrew.name = "Andrew"; ana.next = &andrew; That works fine. But it’s not ideal. Very manual.. We want functions to handle operations so we likely want an “add” function.

What functions we need? Add Add keeping alphabetical order! Delete Search?

The add function What are our parameters? Current list Element to add What’s the current list at the very beginning? What would you consider to be an “empty” list? NULL! Do we need a return value? Yes! Why? To be able to delete the front!

Add function Return type: struct student * Name: Add Parameter 1: struct student * current_list Parameter 2: ? char * name? struct student s1? struct strudent *s2?

Add function struct student *add(struct student *list, char* name) { struct student s; s.name = name; s.next = NULL; if(list == NULL) { return &s; }else { struct student *pos = list; while((*pos).next != NULL) { pos = (*pos).next; } (*pos).next = &s; return list; } } Note: This has a major error!

Before we get to the error – The ‘->’ operator The notation (*pos).next is kind of annoying. Having to “de-reference” the pointer to access the struct’s elements is a very common task We have a special operator that does this! The ‘->’ operator So if ptr is a pointer to a struct that has id as one of the its elements: ptr->id is equivalent to (*ptr).id pos->next is equivalent to (*pos).next

The -> operator struct student *add(struct student *list, char* name) { struct student s; s.name = name; s.next = NULL; if(list == NULL) { return &s; }else { struct student *pos = list; while(pos->next != NULL) { pos = pos->next; } pos->next = &s; return list; } } Note: This has a major error!

If we compile that, we get a warning about the error! list.c:17:3: warning: function returns address of local variable [-Wreturn-local-addr] return &s; ^ The warning is pretty clear. We are returning the memory address of a “local variable” If you remember from our discussion on scopes: A “local variable” is a variable defined inside a function As opposed o a “global variable” that is accessible in the full scope of the program

So what’s the error? struct student *add(struct student *list, char* name) { struct student s; s.name = name; s.next = NULL; if(list == NULL) { return &s; }else { struct student *pos = list; while(pos->next != NULL) { pos = pos->next; } pos->next = &s; return list; } }

Ok… so maybe we could receive the struct? struct student *add(struct student *list, struct student s) { if(list == NULL) { return &s; }else { struct student *pos = list; while(pos->next != NULL) { pos = pos->next; } pos->next = &s; return list; } } This is still an issue… Structs are passed by value And parameters are also local variables…

Can we finally see one version that runs? struct student *add(struct student *list, struct student *s) { if(list == NULL) { return s; }else { struct student *pos = list; while(pos->next != NULL) { pos = pos->next; } pos->next = s; return list; } }

Ok are we happy with add now? Nope. But, why? Right now to add a new student we need to do something like this: struct student s = {.name = “Name”,.next = NULL}; list = add(list, &s); What happens if the user can input the students? How many struct student do we need to allocate? We could potentially allocate an array so that we have structs to take from. The problem with that is: how many are enough? What happens if the user wants just one more than we gave them? It becomes very inneficcient. The solution: malloc!

malloc (also in the Advanced Features Chapter) REALLY? Advanced features??? And pointer arithmetic is part of the pointer chapter?? Sorry I needed to complain about that decision the book author made. malloc is defined in stdlib.h It stands for memory allocation. Malloc “dynamically” allocates memory It receives a single parameter of type size_t with the number of bytes to allocate size_t is a custom type and it’s actual meaning is platform (computer) dependent Usually it is an unsigned long int (but not necessarily) We’ve seen size_t before when we talked about the sizeof function. It returns a void* (a pointer to type void). This is C’s “generic” pointer. It can point to anything! Including code (recall my awkward discussion about calling functions without a name)

malloc So how do I use it? int *ptr_int = (int*)malloc(4); Wait don’t use it like that…. Even if we know that an int is 4 bytes for most of our uses…. This ties our code to architectures that use 4 byte integers. The correct way of using it: int *ptr_int = (int*)malloc(sizeof(int));

malloc – Graphically explained int *ptr_int; ptr_int = (int*)malloc(sizeof(int)); ?

malloc – Graphically explained int *ptr_int; ptr_int = (int*)malloc(sizeof(int)); ? At this point this piece of memory is not named. It is valid memory, but it’s not tied to a variable name.

malloc – Graphically explained int *ptr_int; ptr_int = (int*)malloc(sizeof(int)); ?

So how do we use it for our add function? struct student *add(struct student *list, char* name) { struct student s; s.name = name; s.next = NULL; if(list == NULL) { return &s; }else { struct student *pos = list; while((*pos).next != NULL) { pos = (*pos).next; } (*pos).next = &s; return list; } }

So how do we use it for our add function? struct student *add(struct student *list, char* name) { struct student *s = (struct student*) malloc(sizeof(struct student)); s->name = name; s->next = NULL; if(list == NULL) { return s; }else { struct student *pos = list; while((*pos).next != NULL) { pos = (*pos).next; } (*pos).next = s; return list; } }

Delete function We will delete by index (same as we did before). void delete(struct student *list, int index) { struct student *prev; struct student *current = list; while(index > 0 ) { index--; prev = current; current = current->next; } prev->next = current->next; }

Allowing deleting the head (We all want to get rid of Ana) Ok she is my best friend, so no we don’t…. But if we did... The current way doesn’t support that. We can do it recursively (and we also don’t need to take into account the previous! Which is cool!) struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;}

Freeing memory We are dynamically asking for memory. Remember memory is a limited resource. It is BIG for most of our applications. But it’s not infinite. Every time we call malloc, we are making a commitment to use that memory and eventually free it. Not freeing memory is bad… It’s like punching your mom… like that bad… Ok maybe not THAT bad…. When the program ends, all memory gets reclaimed OS programmers are smart dudes… But we should always try to use memory responsibly

Freeing memory free is the function we use to free up memory we have created using malloc. free receives any pointer, it goes to that piece of memory and let’s the OS reclaim the memory. free(ptr_int);

Delete function struct student *delete(struct student *list, int index) { struct student *prev; struct student *current = list; while(index > 0 ) { index--; prev = current; current = current->next; } prev->next = current->next; free(current); return list; }

Recursive delete struct student *delete(struct student *list, int index) { if(index == 0) { struct student *next = list->next; free(list); return next; }else { list->next = delete(list->next, index-1); return list;} Why like that?

Pointers FRIDAY JULY, 10 TH

Administrative Stuff Quiz today. Quiz #5 grades were released yesterday. Homework #5 was posted. The solution to Homework #4 was also posted. Let’s check the homework specification.

Recursive delete struct student *delete2(struct student *list, int index) { if(index == 0) { struct student *next = list->next; free(list); return next; }else { list->next = delete2(list->next, index-1); return list;}

Recursive delete struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;}

AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list,int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} list = delete2(list, 2); list

delete2(list, 2)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;}

list delete2(, 2 ) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;}

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;}

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;}

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;}

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 2-1)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 1-1)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0)

list delete2(, 2) AnaAndrewCristina Juliana Michael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0)

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0)

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0)

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0)

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0) Juliana

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) Juliana

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) Juliana

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) Juliana

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} Juliana

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} Juliana

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} Juliana

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} Juliana

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} Juliana

list AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { return list->next; }else { list->next = delete2(list->next, index-1); return list;} Juliana

list AnaAndrewCristinaJulianaMichael list = delete2(list, 2); Juliana

list AnaAndrewCristinaJulianaMichaelJuliana

list AnaAndrewCristinaJulianaMichael void print(struct student *head) { while(head != NULL) { printf("%s\n", (*head).name); head = (*head).next; }

list AnaAndrewCristinaJulianaMichael void print(struct student *head) { while(head != NULL) { printf("%s\n", head->name); head = head->next; }

list AnaAndrewCristinaJulianaMichael void print(struct student *head) { while(head != NULL) { printf("%s\n", head->name); head = head->next; } print(list);

list AnaAndrewCristinaJulianaMichael void print(struct student *head) { while(head != NULL) { printf("%s\n", head->name); head = head->next; } print(list); Cristina is no longer accessible from the Head (list). However, she is still in memory.

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { struct student *next = list->next; free(list); return next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0)

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { struct student *next = list->next; free(list); return next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0) next

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { struct student *next = list->next; free(list); return next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0) next

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { struct student *next = list->next; free(list); return next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0) next

list delete2(, 2) AnaAndrewCristinaJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { struct student *next = list->next; free(list); return next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0) next

list delete2(, 2) AnaAndrewJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { struct student *next = list->next; free(list); return next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) delete2(, 0) next

list delete2(, 2) AnaAndrewJulianaMichael struct student *delete2(struct student *list, int index) { if(index == 0) { struct student *next = list->next; free(list); return next; }else { list->next = delete2(list->next, index-1); return list;} delete2(, 1) next

Questions?

Using malloc to create variable size arrays….