Exercise 11 Dynamic allocation and structures. Dynamic Allocation Array variables have fixed size, used to store a fixed and known amount of variables.

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

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.
Dynamic memory allocation
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.
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.
Structures Spring 2013Programming and Data Structure1.
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.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
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:
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
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.
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.
Exercise 11 Dynamic allocation, structures, linked lists.
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
1 Structures, Dynamic Memory Allocation. 2 Agenda Structures Definition & usage Pointers to structures Arrays and pointers in structures Dynamic Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Programming Structures and Dynamic Allocation. Dynamic Memory Allocation The memory requirement of our program is not always known in advance  Arrays.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C Course Lecture 4 This lecture we'll talk about: Multi-dimensional arrays. Pointer arithmetic. Pointers to structures. Multi-file programming. What is.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Outline Midterm results Static variables Memory model
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Functions, Pointers, Structures Keerthi Nelaturu.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Stack and Heap Memory Stack resident variables include:
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.
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.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
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.
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.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 3 – August 28, 2001.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
ECE Application Programming
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
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.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
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.
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.
Computer Organization and Design Pointers, Arrays and Strings in C
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Linked List :: Basic Concepts
Pointers Department of Computer Science-BGU יום שלישי 31 יולי 2018.
Lecture 6 C++ Programming
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
הגדרת משתנים יום שלישי 27 נובמבר 2018
C Programming Strings.
- Dynamic Allocation - Linked lists
EECE.2160 ECE Application Programming
Linked List.
Programming Structures.
EECE.2160 ECE Application Programming
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Exercise 11 Dynamic allocation and structures

Dynamic Allocation Array variables have fixed size, used to store a fixed and known amount of variables – known at the time of compilation This size can’t be changed after compilation However, we don’t always know in advance how much space we would need for an array or a variable We would like to be able to dynamically allocate memory

The malloc function void * malloc(unsigned int nBytes); The function 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

Example dynamic_reverse_array.c

Why casting? The casting in y = (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 this ‘ sizeof ’ ? The sizeof operator gets a variable or a type as an input and outputs its size in bytes: double x; s1=sizeof(x); /* s1 is 8 */ s2=sizeof(int) /* s2 is 4 */

Free the allocated memory segment void free(void *ptr); We use free(p) to free the allocated memory pointed to by p If p doesn’t point to an area allocated by malloc, a run-time error occurs Always remember to free the allocated memory once you don’t need it anymore Otherwise, you may run out of memory before you know it!

Another example another_strcpy.c

Exercise Implement the function my_strcat :  Input – two strings, s1 and s2  Output – a pointer to a dynamically allocated concatenation (‘shirshur’)  For example: The concatenation of “hello_” and “world!” is the string “hello_world!” Write a program that accepts two strings from the user and prints their concatenation  Assume input strings are no longer than a 100 chars

Solution my_strcat.c (my_strcat2.c)

What’s wrong with this? char *my_strcat(char *str1, char *str2) { int len; char result[500]; /* Let’s assume this is large enough */ len = strlen(str1); strcpy(result, str1); strcpy(result+len, str2); return result; }

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 be composed of more than one variable, but are logically units

Structures A struct (short for structure) is a collection of variables of different types, gathered into one super-variable It is used to define more complex data types Variables in a struct are called members or fields

Example – complex numbers. The following is the definition of a new ‘variable’ of type complex number: struct complex { int real; int img; }; Once we define a structure, we can treat it as any type.  In a program, we can then write: struct complex num1, num2, num3;

Access structure members If A is a variable of some structure type with a member named x, then A.x is that member of A  struct complex C; C.real = 0; If pA is a pointer to a structure with a member x, then pA->x is that member of the variable pointed by pA.  This is simply shorthand for (*pA).x struct complex *pc = &C; pc->real = 1;

A more convenient usage with typedef An alternative definition: typedef struct complex_t { int real; int img; } complex; Now the program has a new variable type - “ complex ”. This way we don’t have to write “ struct complex ” every time! For example, we can define two complex numbers in the following line: complex num1, num2;

Examples AddComplex.c IncDate.c

AddComplex – step by step complex a, b, c; printf(“…"); scanf("%lf%lf",&(a.real),&(a.img)); printf(“…"); scanf("%lf%lf",&(b.real),&(b.img)); c = AddComp(a,b); printf(“result = %g+%gi\n",c.real,c.img); return 0; …… realimg a …… realimg b …… realimg c

AddComplex – step by step complex a, b, c; printf(“…"); scanf("%lf%lf",&(a.real),&(a.img)); printf(“…"); scanf("%lf%lf",&(b.real),&(b.img)); c = AddComp(a,b); printf(“result = %g+%gi\n",c.real,c.img); return 0; …… realimg a …… realimg b …… realimg c

AddComplex – step by step complex a, b, c; printf(“…"); scanf("%lf%lf",&(a.real),&(a.img)); printf(“…"); scanf("%lf%lf",&(b.real),&(b.img)); c = AddComp(a,b); printf(“result = %g+%gi\n",c.real,c.img); return 0; realimg a …… realimg b …… realimg c

AddComplex – step by step complex a, b, c; printf(“…"); scanf("%lf%lf",&(a.real),&(a.img)); printf(“…"); scanf("%lf%lf",&(b.real),&(b.img)); c = AddComp(a,b); printf(“result = %g+%gi\n",c.real,c.img); return 0; realimg a …… realimg b …… realimg c

AddComplex – step by step complex a, b, c; printf(“…"); scanf("%lf%lf",&(a.real),&(a.img)); printf(“…"); scanf("%lf%lf",&(b.real),&(b.img)); c = AddComp(a,b); printf(“result = %g+%gi\n",c.real,c.img); return 0; realimg a realimg b …… realimg c

AddComplex – step by step complex a, b, c; printf(“…"); scanf("%lf%lf",&(a.real),&(a.img)); printf(“…"); scanf("%lf%lf",&(b.real),&(b.img)); c = AddComp(a,b); printf(“result = %g+%gi\n",c.real,c.img); return 0; realimg a realimg b …… realimg c

AddComplex – step by step complex AddComp(complex x, complex y) { complex z; z.real = x.real + y.real; z.img = x.img + y.img; return z; } realimg x realimg y …… realimg z

AddComplex – step by step complex AddComp(complex x, complex y) { complex z; z.real = x.real + y.real; z.img = x.img + y.img; return z; } realimg x realimg y …6.0 realimg z

AddComplex – step by step complex AddComp(complex x, complex y) { complex z; z.real = x.real + y.real; z.img = x.img + y.img; return z; } realimg x realimg y realimg z

AddComplex – step by step complex AddComp(complex x, complex y) { complex z; z.real = x.real + y.real; z.img = x.img + y.img; return z; } realimg x realimg y realimg z

AddComplex – step by step complex a, b, c; printf(“…"); scanf("%lf%lf",&(a.real),&(a.img)); printf(“…"); scanf("%lf%lf",&(b.real),&(b.img)); c = AddComp(a,b); printf(“result = %g+%gi\n",c.real,c.img); return 0; realimg a realimg b realimg c

AddComplex – step by step complex a, b, c; printf(“…"); scanf("%lf%lf",&(a.real),&(a.img)); printf(“…"); scanf("%lf%lf",&(b.real),&(b.img)); c = AddComp(a,b); printf(“result = %g+%gi\n",c.real,c.img); return 0; realimg a realimg b realimg c

Miscellaneous structure trivia Structure members may be ordinary variable types, but also other structures and even arrays! Structures can therefore be rather large and take up a lot of space Many times we prefer to pass structures to functions by address, and not by value  Thus a new copy of the structure is not created – just a pointer to the existing structure

More trivia Structures cannot be compared using the == operator  They must be compared member by member  Usually this will be done in a separate function Structures can be copied using the = operator  Member-wise copy

Example Is_In_Circle.c

Is_in_circle – step by step printf(“Enter dot\n"); scanf("%lf%lf",&d.x,&d.y); printf("Enter circle center\n"); scanf("%lf%lf",&c.center.x,&c.center.y); printf("Enter circle radius\n"); scanf("%lf",&c.radius); if (IsInCircle(&d, &c)) printf("dot is in circle\n"); else printf("dot is out of circle\n"); …… yx d (dot)c (circle) …… yx center (dot) radius …

Is_in_circle – step by step printf(“Enter dot\n"); scanf("%lf%lf",&d.x,&d.y); printf("Enter circle center\n"); scanf("%lf%lf",&c.center.x,&c.center.y); printf("Enter circle radius\n"); scanf("%lf",&c.radius); if (IsInCircle(&d, &c)) printf("dot is in circle\n"); else printf("dot is out of circle\n"); …… yx d (dot)c (circle) …… yx center (dot) radius …

Is_in_circle – step by step printf(“Enter dot\n"); scanf("%lf%lf",&d.x,&d.y); printf("Enter circle center\n"); scanf("%lf%lf",&c.center.x,&c.center.y); printf("Enter circle radius\n"); scanf("%lf",&c.radius); if (IsInCircle(&d, &c)) printf("dot is in circle\n"); else printf("dot is out of circle\n"); yx d (dot)c (circle) …… yx center (dot) radius …

Is_in_circle – step by step printf(“Enter dot\n"); scanf("%lf%lf",&d.x,&d.y); printf("Enter circle center\n"); scanf("%lf%lf",&c.center.x,&c.center.y); printf("Enter circle radius\n"); scanf("%lf",&c.radius); if (IsInCircle(&d, &c)) printf("dot is in circle\n"); else printf("dot is out of circle\n"); yx d (dot)c (circle) …… yx center (dot) radius …

Is_in_circle – step by step printf(“Enter dot\n"); scanf("%lf%lf",&d.x,&d.y); printf("Enter circle center\n"); scanf("%lf%lf",&c.center.x,&c.center.y); printf("Enter circle radius\n"); scanf("%lf",&c.radius); if (IsInCircle(&d, &c)) printf("dot is in circle\n"); else printf("dot is out of circle\n"); yx d (dot)c (circle) 0.0 yx center (dot) radius …

Is_in_circle – step by step printf(“Enter dot\n"); scanf("%lf%lf",&d.x,&d.y); printf("Enter circle center\n"); scanf("%lf%lf",&c.center.x,&c.center.y); printf("Enter circle radius\n"); scanf("%lf",&c.radius); if (IsInCircle(&d, &c)) printf("dot is in circle\n"); else printf("dot is out of circle\n"); yx d (dot)c (circle) 0.0 yx center (dot) radius …

Is_in_circle – step by step printf(“Enter dot\n"); scanf("%lf%lf",&d.x,&d.y); printf("Enter circle center\n"); scanf("%lf%lf",&c.center.x,&c.center.y); printf("Enter circle radius\n"); scanf("%lf",&c.radius); if (IsInCircle(&d, &c)) printf("dot is in circle\n"); else printf("dot is out of circle\n"); yx d (dot)c (circle) 0.0 yx center (dot) radius 5

Is_in_circle – step by step printf(“Enter dot\n"); scanf("%lf%lf",&d.x,&d.y); printf("Enter circle center\n"); scanf("%lf%lf",&c.center.x,&c.center.y); printf("Enter circle radius\n"); scanf("%lf",&c.radius); if (IsInCircle(&d, &c)) printf("dot is in circle\n"); else printf("dot is out of circle\n"); yx d (dot)c (circle) 0.0 yx center (dot) radius 5

Is_in_circle – step by step int IsInCircle(dot *p_dot, circle *p_circle) { double x_dist,y_dist; x_dist = p_dot->x - p_circle->center.x; y_dist = p_dot->y - p_circle->center.y; if (x_dist*x_dist + y_dist*y_dist radius*p_circle->radius) return 1; return 0; } yx (dot)(circle) 0.0 yx center (dot) radius 5 x_disty_dist …… p_circlep_dot

Is_in_circle – step by step int IsInCircle(dot *p_dot, circle *p_circle) { double x_dist,y_dist; x_dist = p_dot->x - p_circle->center.x; y_dist = p_dot->y - p_circle->center.y; if (x_dist*x_dist + y_dist*y_dist radius*p_circle->radius) return 1; return 0; } yx (dot)(circle) 0.0 yx center (dot) radius 5 x_disty_dist 1.0… p_circlep_dot

Is_in_circle – step by step int IsInCircle(dot *p_dot, circle *p_circle) { double x_dist,y_dist; x_dist = p_dot->x - p_circle->center.x; y_dist = p_dot->y - p_circle->center.y; if (x_dist*x_dist + y_dist*y_dist radius*p_circle->radius) return 1; return 0; } yx (dot)(circle) 0.0 yx center (dot) radius 5 x_disty_dist p_circlep_dot

Is_in_circle – step by step int IsInCircle(dot *p_dot, circle *p_circle) { double x_dist,y_dist; x_dist = p_dot->x - p_circle->center.x; y_dist = p_dot->y - p_circle->center.y; if (x_dist*x_dist + y_dist*y_dist radius*p_circle->radius) return 1; return 0; } yx (dot)(circle) 0.0 yx center (dot) radius 5 x_disty_dist p_circlep_dot

Is_in_circle – step by step int IsInCircle(dot *p_dot, circle *p_circle) { double x_dist,y_dist; x_dist = p_dot->x - p_circle->center.x; y_dist = p_dot->y - p_circle->center.y; if (x_dist*x_dist + y_dist*y_dist radius*p_circle->radius) return 1; return 0; } yx (dot)(circle) 0.0 yx center (dot) radius 5 x_disty_dist p_circlep_dot

Is_in_circle – step by step printf(“Enter dot\n"); scanf("%lf%lf",&d.x,&d.y); printf("Enter circle center\n"); scanf("%lf%lf",&c.center.x,&c.center.y); printf("Enter circle radius\n"); scanf("%lf",&c.radius); if (IsInCircle(&d, &c)) printf("dot is in circle\n"); else printf("dot is out of circle\n"); yx d (dot)c (circle) 0.0 yx center (dot) radius 5

Exercise Implement the MultComplex function:  Input – two complex numbers  Output – their multiplication  Note: if x=a+ib and y=c+id then: z = xy = (ac-bd)+i(ad+bc) Write a program that uses the above function to multiply two complex numbers given by the user

Solution MultiplyComplex.c

Exiting the program void exit(int status); Sometimes an error occurs and we want the program to immediately exit The exit function closes all open files, frees all allocated memory, and exits the program Equivalent to calling ‘return’ within main Remember to #include See strcpy_with_exit.c

Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure that contains a member which is an array, the array is copied element by element  Not just the address gets copied  For example - array_member.c Reminder – ordinary arrays can’t be copied simply by using the ‘=‘ operator  They must be copied using a loop

Structures containing arrays When passing the structure to a function by value  Changing the array field inside the function won’t change it in the calling function Reminder – when passing an ordinary array to a function, all that gets passed is the address of its first element  Hence every change to the array within the function, changes the array in the calling function

Pointers are another matter If the member is a pointer, for example to a dynamically allocated array, all that gets copied is the pointer (the address) itself  For example, pointer_member.c Hence, we should take extra care when manipulating structures that contain pointers