Programming Structures and Dynamic Allocation. Dynamic Memory Allocation The memory requirement of our program is not always known in advance  Arrays.

Slides:



Advertisements
Similar presentations
Structures Often we want to be able to manipulate logical entities as a whole For example, complex numbers, dates, student records, etc Each of these must.
Advertisements

Lectures 10 & 11.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
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.
Elementary Data Structures: Part 2: Strings, 2D Arrays, Graphs
CSCI 171 Presentation 11 Pointers. Pointer Basics.
C Programming : Dynamic memory allocation & Structures 2008/11/19 Made by Jimin Hwa Edited and presented by Souneil Park
Kernighan/Ritchie: Kelley/Pohl:
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.
CS100A, Fall 1997, Lecture 241 CS100A, Fall 1997 Lecture 24, Tuesday 25 November (There were no written notes for lecture 23 on Nov. 20.) Data Structures.
1 CSE 303 Lecture 12 structured data reading: Programming in C Ch. 9 slides created by Marty Stepp
Exercise 11 Dynamic allocation, structures, linked lists.
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.
Exercise 11 Dynamic allocation and structures. Dynamic Allocation Array variables have fixed size, used to store a fixed and known amount of variables.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
1 Structures, Dynamic Memory Allocation. 2 Agenda Structures Definition & usage Pointers to structures Arrays and pointers in structures Dynamic Memory.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CS 61C L04 C Structures, Memory Management (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
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.
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.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
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.
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:
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.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Structures Combining data types into a logical groupings.
CS 261 – Data Structures Introduction to C Programming.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
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.
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
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.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
C Structures and Memory Allocation
Computer Organization and Design Pointers, Arrays and Strings in C
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
2016.
Pointers Department of Computer Science-BGU יום שלישי 31 יולי 2018.
C Basics.
Programming Languages and Paradigms
Lecture 6 C++ Programming
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
הגדרת משתנים יום שלישי 27 נובמבר 2018
Dynamic Memory Allocation
Memory Allocation CS 217.
C Programming Strings.
- Dynamic Allocation - Linked lists
EECE.2160 ECE Application Programming
Outline Defining and using Pointers Operations on pointers
Programming Structures.
C Structures and Memory Allocation
Dynamic Memory – A Review
Module 13 Dynamic Memory.
Presentation transcript:

Programming Structures and Dynamic Allocation

Dynamic Memory Allocation The memory requirement of our program is not always known in advance  Arrays have fixed size determined at compile time We would like to allocate at runtime

The Memory Two Parts: 1. Stack  Memory is allocated when entering a function  Deallocation when the function terminates 2. Heap  Programmer control allocation and deallocation

Memory Management stdlib.h Two operations for memory management 1. Allocation  void* malloc(…); 2. Deallocation  void free(…);

The malloc Function void* malloc(unsigned int nBytes); malloc is used to dynamically allocate nBytes in memory malloc returns a pointer to the allocated area on success, NULL on failure You should always check whether memory was successfully allocated Remember to #include

The free Function void free(void *ptr); Use free(p) to deallocate memory pointed by p If p doesn’t point to an area allocated by malloc an error occurs  No partial deallocation Always remember to free the allocated memory once you are done with it

Example int main(void) { int i, n, *p; printf("How many numbers will you enter?\n"); scanf("%d", &n); /* Allocate an int array of the proper size */ p = (int*)malloc(n * sizeof(int)); if (p == NULL) { printf("Memory allocation failed!\n"); return 1; }... /* Free the allocated space */ free(p); return 0; }

Why Casting? The casting in p = (int *)malloc(n*sizeof(int)); is needed because malloc returns void* : void* malloc(unsigned int nbytes); The type ( void* ) specifies a general pointer, which can be cast to any pointer type.

What is ‘ sizeof ’ ? The sizeof operator gets a variable or a type as an input and return its size in bytes sizeof always calculates the size of the type double x; s1 = sizeof(x); /* s1 is 8 */ s2 = sizeof(int) /* s2 is 4 */

Example char name[25]; char* address = (char*)malloc(25); int i; printf("sizeof(name) = %d\n", sizeof(name)); printf("sizeof(address) = %d\n", sizeof(address)); if (sizeof(&i) == sizeof(address)) printf("True\n"); else printf("False\n"); 25 4 True

Returning Allocated Memory Since allocated memory is not deallocated upon function termination we can return its address. Duplicate a string char* strdup(const char* str) { char* dup = (char*)malloc((strlen(str)+1) * sizeof(char)); if (dup != NULL) { strcpy(dup, str); } return dup; }

Exercise Implement the function char* my_strcat(const char *s1, const char *s2);  Output – a pointer to a dynamically allocated concatenation of s1 and s2  For example: The concatenation of “hello_” and “world!” is the string “hello_world!” Test your function

Solution char* my_strcat(const char *s1, const char *s2) { int len; char *result = NULL; len = strlen(s1) + strlen(s2) + 1; result = (char*)malloc(len * sizeof(char)); if (result == NULL) { printf(“Memory allocation failed!\n"); return NULL; } strcpy(result, s1); strcat(result, s2); return result; }

What’s Wrong Here? char* my_strcat(const char *s1, const char *s2) { int len; char result[500]; /* assume this is enough */ strcpy(result, s1); strcpy(result + strlen(s1), s2); return result; }

Pitfalls Accessing un-initialized pointer int* p; *p = 3; Using de-allocated memory int* p = (int*)malloc(SIZE * sizeof(int));... /* do something with p*/ free(p); *p = 0;

Structures Not much in the real world comes to us as simple data types. (e.g. Car, Book, Bank account) We want to be able to manipulate logical entities as a whole The individual pieces of the data may exist in one of the basic forms How do you keep track of what pieces of the data belong together?

Examples Book  Title, Authors, ISBN, Publisher Bank Account  Owners, Balance, Credit Car  Make, Model, Year

A convenient way of grouping several pieces of related information together. A collection of variables under a single name. Structures - User Defined Types

Structures - Example struct point { double x; double y; }; struct rectangle { struct point low_left; struct point up_right; }; struct student { char id[10]; char* name; int avg_grade; }; struct point { double x, y; };

Defining a struct struct struct-name { type field-name1; type field-name2; type field-name3;... };

Example - Complex Numbers Structure declaration Variable definition  Define variables of type complex struct complex { double real, img; }; struct complex c1, c2;

Field Access Use the. (dot) operator to access a field in a structure. If comp is of type complex then to access the real part we write comp.real and to access the imaginary part we write comp.img

Example Printing a complex number printf("%g + %gi", comp.real, comp.img); Input from the user scanf("%lf", &comp.real);

Typdef Introduce synonyms for types typedef int Boolean; typedef char* String; Boolean b; String str = "Text";

Typdef and Structs Instead of writing struct complex everywhere we can create a shorter synonym using typedef. typdef struct complex Complex Then use it Complex c1, c2;

We can combine the typdef with the structure declaration: typedef struct complex { int real; int img; } Complex; This is the common way to define new types Typedef Even Shorter

Structures and Functions Function can receive structures as their parameters and return structures as their return value Parameter passing is done by value  copy Similar to basic types

Structures and Functions - Example Complex make_complex(double real, double img) { Complex temp; temp.real = real; temp.img = img; return temp; } Complex add_complex(Complex c1, Complex c2) { return make_comlex(c1.real + c2.real, c1.img + c2.img); }

add_complex – step by step int main(void) { Complex a, b, sum; printf("…"); scanf("%lf%lf", &(a.real), &(a.img)); printf("…"); scanf("%lf%lf", &(b.real), &(b.img)); sum = add_complex(a, b); printf("result = %g+%gi\n", sum.real, sum.img); return 0; } …… realimg a …… realimg b …… realimg sum

add_complex – step by step int main(void) { Complex a, b, sum; printf("…"); scanf("%lf%lf", &(a.real), &(a.img)); printf("…"); scanf("%lf%lf", &(b.real), &(b.img)); sum = add_complex(a, b); printf("result = %g+%gi\n", sum.real, sum.img); return 0; } …… realimg a …… realimg b …… realimg sum

add_complex – step by step int main(void) { Complex a, b, sum; printf("…"); scanf("%lf%lf", &(a.real), &(a.img)); printf("…"); scanf("%lf%lf", &(b.real), &(b.img)); sum = add_complex(a, b); printf("result = %g+%gi\n", sum.real, sum.img); return 0; } realimg a …… realimg b …… realimg sum

add_complex – step by step int main(void) { Complex a, b, sum; printf("…"); scanf("%lf%lf", &(a.real), &(a.img)); printf("…"); scanf("%lf%lf", &(b.real), &(b.img)); sum = add_complex(a, b); printf("result = %g+%gi\n", sum.real, sum.img); return 0; } realimg a …… realimg b …… realimg sum

add_complex – step by step int main(void) { Complex a, b, sum; printf("…"); scanf("%lf%lf", &(a.real), &(a.img)); printf("…"); scanf("%lf%lf", &(b.real), &(b.img)); sum = add_complex(a, b); printf("result = %g+%gi\n", sum.real, sum.img); return 0; } realimg a realimg b …… realimg sum

add_complex – step by step int main(void) { Complex a, b, sum; printf("…"); scanf("%lf%lf", &(a.real), &(a.img)); printf("…"); scanf("%lf%lf", &(b.real), &(b.img)); sum = add_complex(a, b); printf("result = %g+%gi\n", sum.real, sum.img); return 0; } realimg a realimg b …… realimg sum

add_complex – step by step Complex add_complex(Complex x, Complex y) { Complex sum; sum.real = x.real + y.real; sum.img = x.img + y.img; return sum; } realimg x realimg y …… realimg sum

add_complex – step by step Complex add_complex(Complex x, Complex y) { Complex sum; sum.real = x.real + y.real; sum.img = x.img + y.img; return sum; } realimg x realimg y …6.5 realimg sum

add_complex – step by step Complex add_complex(Complex x, Complex y) { Complex sum; sum.real = x.real + y.real; sum.img = x.img + y.img; return sum; } realimg x realimg y realimg sum

add_complex – step by step Complex add_complex(Complex x, Complex y) { Complex sum; sum.real = x.real + y.real; sum.img = x.img + y.img; return sum; } realimg x realimg y realimg sum

add_complex – step by step int main(void) { Complex a, b, sum; printf("…"); scanf("%lf%lf", &(a.real), &(a.img)); printf("…"); scanf("%lf%lf", &(b.real), &(b.img)); sum = add_complex(a, b); printf(“result = %g+%gi\n", sum.real, sum.img); return 0; } realimg a realimg b realimg sum

add_complex – step by step int main(void) { Complex a, b, sum; printf("…"); scanf("%lf%lf", &(a.real), &(a.img)); printf("…"); scanf("%lf%lf", &(b.real), &(b.img)); sum = add_complex(a, b); printf(“result = %g+%gi\n", sum.real, sum.img); return 0; } realimg a realimg b realimg sum

add_complex – step by step int main(void) { Complex a, b, sum; printf("…"); scanf("%lf%lf", &(a.real), &(a.img)); printf("…"); scanf("%lf%lf", &(b.real), &(b.img)); sum = add_complex(a, b); printf(“result = %g+%gi\n", sum.real, sum.img); return 0; } realimg a realimg b realimg sum

Assignment Structures can be assigned (copied) using the assignment operator “=”  Bitwise copy – copying the content of one structure’s memory onto another c1 = add_complex(…); c1c

Arrays in Structs The entire array is part of the structure When passing the struct to a function (by value)  Changing the array field won’t change the original array

Pointers in Structs When copying a struct containing a pointer only the pointer is copied (shallow copy) Not what the pointer points to we should take extra care when manipulating structures that contain pointers

Comparison Structures cannot be compared using the equality operator “==”  They must be compared member by member  Usually this will be done in a separate function is_equal_complex(Complex c1, Complex c2) { return (c1.real == c2.real) && (c1.img == c2.img); }

Exercise Implement a multiply_complex function: Complex multiply_complex(Complex x, Complex y);  Note: if x = a + b i and y = c + d i then: z = xy = (ac - bd) + (ad + bc) i Write a program that uses the above function to multiply two complex numbers given by the user

Solution Complex make_complex(double real, double img) { Complex temp; temp.real = real; temp.img = img; return temp; } Complex multiply_complex(Complex a, Complex b) { return make_complex(a.real * b.real - a.img * b.img, a.real * b.img + a.img * b.real); }

Pointers to Structures Same as with other types Pointer definition  structure-name * variable-name; Complex* comptr; Complex c, *cptr; cptr = &c; defines a complex and a pointer to a complex assign the address of the complex variable to the complex pointer

To access the fields we can write: (*pcomp).real (*pcomp).img Complex comp; Complex *pcomp = ∁ Accessing Fields Using Pointers

Alternative Syntax Pointer to structures are extremely common Alternative notation as a shorthand  p →member-of-structure  → is minus sign followed by > Example  pcomp→real  pcomp→img

Example typdef struct point { double x, y; } Point; typdef struct rect { Point pt1, pt2; } Rect; Rect r, *rp = &r; r.pt1.x (*rp).pt1.x rp->pt1.x equivalent

Example typedef struct point { double x; double y; } Point; typedef struct circle { Point center; double radius; } Circle;

Example int is_in_circle(Point *p, Circle *c) { double x_dist, y_dist; x_dist = p->x - c->center.x; y_dist = p->y - c->center.y; return (x_dist * x_dist + y_dist * y_dist radius * c->radius); } A point is in a circle if its distance from the center is smaller than the radius.

Exit void exit(int status); Sometimes an error occurs and we want the program to immediately exit (e.g. division by zero, memory allocation failure) exit terminates the program de-allocates all resources (close open files, free memory, …) To be used only in extreme situations Remember to #include