1 Structures, Dynamic Memory Allocation. 2 Agenda Structures Definition & usage Pointers to structures Arrays and pointers in structures Dynamic Memory.

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
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.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
ספטמבר 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:
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:
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Exercise 11 Dynamic allocation, structures, linked lists.
1 More on Pointers. 2 Reminder 3 Pointers Pointer is a variable that contains the address of a variable Here P is said to point to the variable C C 7.
Exercise 11 Dynamic allocation and structures. Dynamic Allocation Array variables have fixed size, used to store a fixed and known amount of variables.
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.
Programming Structures and Dynamic Allocation. Dynamic Memory Allocation The memory requirement of our program is not always known in advance  Arrays.
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
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.
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.
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:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
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
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
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.
1/15/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 11 (C-5)
Computer Programming for Engineers
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
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
Chapter 19 Data Structures
C Programming Tutorial – Part I
Pointers Department of Computer Science-BGU יום שלישי 31 יולי 2018.
CSCI206 - Computer Organization & Programming
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
Dynamic Memory – A Review
Presentation transcript:

1 Structures, Dynamic Memory Allocation

2 Agenda Structures Definition & usage Pointers to structures Arrays and pointers in structures Dynamic Memory Allocation

3 Structures ‘Logical entities’ Examples: complex numbers, dates, student records, geometric objects, etc’ Each is composed of a number of variables

4 Structures struct: collection of variables, gathered into one variable Defines new data types Memory Variables in a struct are called members or fields

5 Example – complex numbers Definition of a new ‘type’ that represents a complex number: struct complex { int real; int img; }; Once we define a structure, we can use it as any type: struct complex num1, num2, num3;

6 Access structure members If A is of some structure with a member named x, then A.x is that member of A struct complex C; C.real = 0; If A is a pointer to a structure with a member x, then A->x is that member of the variable pointed by A (same as (*A).x) struct complex *pc = &C; pc->real = 1;

7 Convenient usage with typedef typedef struct complex_t { int real; int img; } complex; A new variable type: “complex” Saves writing “struct complex” every time! Usage: complex num1, num2;

8 Examples (AddComplex.c) complex AddComp (complex x, complex y) { complex z; z.real = x.real + y.real; z.img = x.img + y.img; return z; } Structures are passed to functions “by value” A copy of the structure is passed

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 Exercise Implement the MultComplex function – Input - two complex numbers Output – their multiplication Definition: 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

22 Solution (MultiplyComplex.c) complex MultiplyComp(complex a, complex b) { complex c; c.real = a.real*b.real - a.img*b.img; c.img = a.real*b.img + a.img*b.real; return c; }

23 More on Structures Structure members: ordinary variable types, structures, arrays Passing structures to functions by address A copy of the structure is not created – just a pointer to the existing structure

24 More on Structures 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

25 Example (Is_In_Circle.c) 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; }

26 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 …

27 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 …

28 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 …

29 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 …

30 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 …

31 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 …

32 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

33 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

34 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

35 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

36 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

37 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

38 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

39 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

40 Exercise Write a struct that represents a date (day, month, year) Write a function that increments the date void IncDate(Date *d); For example – >

41 Solution IncDate.c

42 Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array ‘=‘: the array is copied element by element It is not the address that 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

43 Structures containing arrays Same behavior when passing the structure to a function Changing the array 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

44 Pointers are another matter If the member is a pointer all that gets copied is the pointer (the address) itself For example, pointer_member.c Make sure that you understand what you do!

45 Dynamic Memory Allocation

46 Dynamic Memory Allocation: Motivation Array variables have fixed size (e.g.: int – 4 bytes, char – 1 byte) This can’t be changed after compilation It is not always known how many elements we will need in runtime We would like to be able to dynamically allocate memory

47 The malloc function void *malloc(unsigned int n); The function malloc is used to dynamically allocate n bytes malloc returns a pointer to the allocated area on success, NULL on failure

48 The malloc function void *malloc(unsigned int n); We should always check whether memory was successfully allocated Remember to #include Allocated memory must be freed (later)

49 Usage Example int n, *p; printf("How many numbers do you want to enter?\n"); scanf("%d",&n); p = (int *)malloc(n*sizeof(int)); if(p == NULL) { printf("Memory allocation failed!\n"); return 1; } free(p);

50 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.

51 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 */

52 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

53 Free the allocated memory segment void free(void *ptr); Always remember to free the allocated memory once you don’t need it Otherwise, you may run out of memory – a common bug that is hard to detect

54 Example dynamic_reverse_array.c

55 Example (dynamic_reverse_array.c) int i, n, *p; printf("How many numbers do you want to enter?\n"); scanf("%d",&n); p = (int *)malloc(n*sizeof(int)); if(p == NULL) { printf("Memory allocation failed!\n"); return 1; } printf("Please enter numbers now:\n"); for(i=0; i<n; i++) scanf("%d", &p[i]); printf("The numbers in reverse order are - \n"); for(i=n-1; i>=0; i--) printf("%d ",p[i]); free(p);

56 Allocating memory within a function Dynamic allocation of memory is not deleted when we leave the scope / exit a function This is why we need to free it Now we are able to allocate memory within a function and use it outside

57 Example (another_strcpy.c) char *another_strcpy(char *src) { char *dst; int len, i; len=strlen(src); dst=(char*)malloc(sizeof(char)*(len+1)); if(dst == NULL) { printf("Memory allocation failed!\n"); return NULL; } for(i=0;i<=len;i++) dst[i] = src[i]; return dst; }

58 Exercise home) 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

59 Solution my_strcat.c (my_strcat2.c)

60 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; }

61 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