ECE Application Programming

Slides:



Advertisements
Similar presentations
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Advertisements

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.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
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.
ECE Application Programming
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
ECE Application Programming
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
ECE Application Programming
Stack and Heap Memory Stack resident variables include:
ECE Application Programming
ECE Application Programming
Linked List :: Basic Concepts
ECE Application Programming
ECE Application Programming
Lectures linked lists Chapter 6 of textbook
ECE Application Programming
ECE Application Programming
ECE Application Programming
ECE Application Programming
Arrays & Dynamic Memory Allocation
EECE.2160 ECE Application Programming
Prof. Neary Adapted from slides by Dr. Katherine Gibson
CSC215 Lecture Memory Management.
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Instructor: Dr. Michael Geiger Spring 2019 Lecture 13: Exam 1 Preview
EECE.2160 ECE Application Programming
Instructor: Dr. Michael Geiger Spring 2019 Lecture 4: Functions in C++
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Instructor: Dr. Michael Geiger Spring 2017 Lecture 12: Exam 1 Preview
EECE.2160 ECE Application Programming
Instructor: Dr. Michael Geiger Spring 2019 Lecture 23: Exam 2 Preview
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Dynamic Memory – A Review
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Presentation transcript:

16.216 ECE Application Programming Instructor: Dr. Michael Geiger Summer 2013 Lecture 11: Dynamically allocated data structures Exam 3 Preview

ECE Application Programming: Lecture 11 Lecture outline Announcements/reminders Program 9 due today Exam 3 Thursday, 8/15 Review Structures Dynamic memory allocation Today’s lecture Dynamically allocated data structures Exam 3 Preview 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Review: Structures User-defined types; example: typedef struct { char first[50]; char middle; char last[50]; unsigned int ID; double GPA; } StudentInfo; Can define variables of that type Scalar: StudentInfo student1; Array: StudentInfo classList[10]; Pointer: StudentInfo *sPtr; Access members using Dot operator: student1.middle = ‘J’; Arrow (if pointers): sPtr->GPA = 3.5; Typically passed to functions by address 5/19/2018 ECE Application Programming: Lecture 11

Review: dynamic memory allocation Basic block allocation: void *malloc(size_t size); Allocate block and clear it: void *calloc(size_t nmemb, size_t size); Resize previously allocated block: void *realloc(void *ptr, Deallocation function: void free(void *ptr); 5/19/2018 ECE Application Programming: Lecture 11

Review: dynamic memory allocation Pitfalls: Memory leaks: must free memory before changing pointer Dangling pointers: reassign pointer after calling free() Dynamically allocated array arr = (int *)malloc(n * sizeof(int)); Can then use array notation: arr[i] = 0; Note that return value from allocation functions must be type cast to correct type 5/19/2018 ECE Application Programming: Lecture 11

Dynamically allocated strings Strings  arrays of characters Basic allocation: based on string length sizeof(char) is always 1 Need to account for null character Example: copying from s to str char *str = (char *)malloc(strlen(s) + 1); strcpy(str, s); Note: dynamically allocated strings must be deallocated when you are done with them 5/19/2018 ECE Application Programming: Lecture 11

Dynamically allocated 2D arrays Think of each row as 1D array 2D array: an array of 1D arrays Since array is technically a pointer, 2D array can be implemented as array of pointers Data type: “pointer to pointer” Example: int **twoDarr; 1st dimension depends on # rows twoDarr = (int **)malloc(nRows * sizeof(int *)); 2nd dimension depends on # columns Must allocate for each row for (i = 0; i < nRows; i++) twoDarr[i] = (int *)malloc(nCols * sizeof(int)); 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Example Complete each of the following functions char *readLine(): Read a line of data from the standard input, store that data in a dynamically allocated string, and return the string (as a char *) Hint: Read the data one character at a time and repeatedly reallocate space in the string int **make2DArray(int total, int nR): Given the total number of values and number of rows to be stored in a two-dimensional array, determine the appropriate number of columns, allocate the array, and return its starting address Note: if nR does not divide evenly into total, round up. In other words, an array with 30 values and 4 rows should have 8 columns, even though 30 / 4 = 7.5 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Solution char *readLine() { char c; // Input character char *str = NULL; // String to hold line int n = 1; // Length of str // Repeatedly store character in str until // '\n' is read; resize str to hold char while ((c = getchar()) != '\n') { str = (char *)realloc(str, n+1); str[n-1] = c; n++; } str[n-1] = '\0'; // Null terminator return str; 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Solution (continued) int **make2DArray(int total, int nR) { int **arr; // 2-D array int nCols; // # of columns int i; // Row index // Calculate nCols; round up if nR does not divide evenly nCols = total / nR; if ((total % nR) != 0) nCols++; // Allocate array--first array of rows, then each row arr = (int **)malloc(nR * sizeof(int *)); for (i = 0; i < nR; i++) arr[i] = (int *)malloc(nCols * sizeof(int)); return arr; } 5/19/2018 ECE Application Programming: Lecture 11

Dynamic allocation and structures Can use sizeof() to get # bytes in structure Examples (using StudentInfo struct): StudentInfo *p; p = (StudentInfo *)malloc(sizeof(StudentInfo)); StudentInfo *arr; int n; printf("Enter array size: "); scanf("%d", &n); arr = (StudentInfo *)malloc(n * sizeof(StudentInfo)); 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Data structures Data structure: way of storing and organizing data Arrays are one relatively inefficient example Other structures designed to optimize: Organizing / sorting data Adding new data Removing unwanted data Searching for data 5/19/2018 ECE Application Programming: Lecture 11

Pointer-based data structures Many structures extensively use pointers Each element within structure contains data + pointer(s) to one or more other elements Usually functions for common operations Add new element Dynamically allocate new element Modify appropriate pointer(s) in other element(s) to point to new element Set pointer(s) in new element to point to other(s) Delete element Modify pointer(s) in other element(s) so they don’t point to element being removed Deallocate removed element Find element Follow pointers to move from one element to next 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Linked list Simple pointer-based structure: linked list Each element (node) contains data + pointer to next element in list Last element points to NULL Program using list needs pointer to first node Image source: http://en.wikipedia.org/wiki/Linked_list 5/19/2018 ECE Application Programming: Lecture 11

Linked list definition Structure to hold list of integers typedef struct node { int value; // Data struct node *next; // Pointer to // next node } LLnode; Note definition style has changed slightly Type “name” both before and after { } Name before (struct node) is necessary to use type inside structure definition Name after (LLnode) can be used in rest of program 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Adding to list Simplest form (unordered list): add new item to beginning of list LLnode *addNode(LLnode *list, int v) { LLnode *newNode; // Allocate space for new node; exit if error newNode = (LLnode *)malloc(sizeof(LLnode)); if (newNode == NULL) { fprintf(stderr, "Error: could not allocate new node\n"); exit(0); } newNode->value = v; // Copy value to new node newNode->next = list; // next points to old list return newNode; 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Examples Write functions for Finding item in list: LLnode *findNode(LLnode *list, int v); Function should return pointer to node if found Return NULL otherwise Removing item from list LLnode *delNode(LLnode *list, int v); Must deallocate space for deleted node Function should return pointer to start of list after it has been modified Note: removing first element in list is special case 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Sorted linked list Can ensure each item is sorted as it’s added Slower item insertion, but faster search Not easy with arrays: must move existing data Keeping linked list sorted Find appropriate location Often done by going “past” appropriate spot Modify pointers Node before correct spot points to new node New node points to node after correct spot Image source: http://en.wikipedia.org/wiki/Linked_list 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Examples Write functions for: Adding item to sorted list: LLnode *addSortedNode(LLnode *list, int v); Use addNode() as a starting point Instead of adding node at beginning, find appropriate place in list and then add Function should return pointer to start of list after it has been modified Finding item in sorted list: LLnode *findSortedNode(LLnode *list, int v); Use findNode() as starting point—should perform same operation, but more efficiently Function should return pointer to node if found Return NULL otherwise 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Exam 3 notes Allowed one 8.5” x 11” two-sided note sheet No other notes or electronic devices Exam lasts 3 hours (but is written for ~50 min) Covers all lectures after Exam 2 (lec. 8-11) Format similar to Exams 1/2 1 multiple choice problem (likely dynamic memory allocation, although that topic may show up elsewhere) 1 code reading problem 1 code writing problem Can look at old exams on web, but we’ve covered some material in more depth than before (file I/O, structures, dynamic memory allocation) 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Review: File I/O Open file: FILE *fopen(filename, file_access) Close file: fclose(file_handle) Formatted I/O: fprintf(file_handle, format_specifier, 0+ variables) fscanf(file_handle, format_specifier, 0+ variables) Unformatted I/O: size_t fwrite(pointer, element size, # elements, file_handle) size_t fread(pointer, element size, # elements, file_handle) Check for EOF using either fscanf() result or feof(FILE *) 5/19/2018 ECE Application Programming: Lecture 11

Review: General I/O (cont.) Character I/O int fputc(int c, FILE *stream); int putchar(int c); int fgetc(FILE *stream); int getchar(); int ungetc(int c, FILE *stream); Line I/O int fputs(const char *s, FILE *stream); int puts(const char *s); char *fgets(char *s, int n, FILE *stream); char *gets(char *s); 5/19/2018 ECE Application Programming: Lecture 11

Review: bit manipulation Bitwise operators: | & ^ ~ Used for desired logical operations Used to set/clear bits Bit shifts: << >> Used to shift bits into position Used for multiplication/division by powers of 2 Common operations Setting/clearing/flipping individual bit Setting/clearing/flipping multiple bits 5/19/2018 ECE Application Programming: Lecture 11

Review: hexadecimal output To print a number in hex, use %x or %X %x prints characters a-f in lowercase %X prints characters A-F in uppercase To show leading 0x, use the # flag To show leading 0s, use precision with total # chars Field width + 0 flag also works unless value = 0 Examples (assume var1 = 0x1A2B) printf(“%x”, var1)  1a2b printf(“%X”, var1)  1A2B printf(“%#x”, var1)  0x1a2b printf(“%.6x”, var1)  001a2b printf(“%#.6x”, var1)  0x001a2b 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Review: Structures User-defined types; example: typedef struct { char first[50]; char middle; char last[50]; unsigned int ID; double GPA; } StudentInfo; Can define variables of that type Scalar: StudentInfo student1; Array: StudentInfo classList[10]; Pointer: StudentInfo *sPtr; Access members using Dot operator: student1.middle = ‘J’; Arrow (if pointers): sPtr->GPA = 3.5; Typically passed to functions by address 5/19/2018 ECE Application Programming: Lecture 11

Review: dynamic memory allocation Basic block allocation: void *malloc(size_t size); Allocate block and clear it: void *calloc(size_t nmemb, size_t size); Resize previously allocated block: void *realloc(void *ptr, Deallocation function: void free(void *ptr); 5/19/2018 ECE Application Programming: Lecture 11

Review: dynamic memory allocation Pitfalls: Memory leaks: must free memory before changing pointer Dangling pointers: reassign pointer after calling free() Dynamically allocated array arr = (int *)malloc(n * sizeof(int)); Can then use array notation: arr[i] = 0; Note that return value from allocation functions must be type cast to correct type 5/19/2018 ECE Application Programming: Lecture 11

Review: dynamically allocated arrays arr = (int *)malloc(n * sizeof(int)); Can then use array notation: arr[i] = 0; 2-D array Data type: “pointer to pointer”: int **twoDarr; 1st dimension depends on # rows twoDarr = (int **)malloc(nRows * sizeof(int *)); 2nd dimension depends on # columns Must allocate for each row for (i = 0; i < nRows; i++) twoDarr[i] = (int *)malloc(nCols * sizeof(int)); 5/19/2018 ECE Application Programming: Lecture 11

Review: pointer-based data structures Data structures to optimize data organization Structure containing pointer(s) to other structure Adding data: allocate space for new node, then adjust pointers Deleting data: adjust pointers, then free space for node Example: linked list typedef struct node { int value; // Data struct node *next; // Pointer to // next node } LLnode; Image source: http://en.wikipedia.org/wiki/Linked_list 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Review: Adding to list Simplest form (unordered list): add new item to beginning of list LLnode *addNode(LLnode *list, int v) { LLnode *newNode; // Allocate space for new node; exit if error newNode = (LLnode *)malloc(sizeof(LLnode)); if (newNode == NULL) { fprintf(stderr, "Error: could not allocate new node\n"); exit(0); } newNode->value = v; // Copy value to new node newNode->next = list; // next points to old list return newNode; 5/19/2018 ECE Application Programming: Lecture 11

Review: deleting from list LLnode *delNode(LLnode *list, int v) { LLnode *cur = list;// Pointer to current node--initially start of list LLnode *prev = NULL;// Pointer to node before cur--initially NULL // Loop will search list, stopping either when list ends or value is found while ((cur != NULL) && (cur->value != v)) { prev = cur; cur = cur->next; } // Data wasn't found--return unmodified list if (cur == NULL) return list; // Data is in first node--must change pointer to start of list if (prev == NULL) list = list->next; // Otherwise, set next pointer in prev (node before one being // removed) to point past node being removed else prev->next = cur->next; free(cur); return list; 5/19/2018 ECE Application Programming: Lecture 11

Review: finding data in list LLnode *findNode(LLnode *list, int v) { LLnode *n = list;// Start with first node // Search until after last node while (n != NULL) { if (n->value == v) // Data found return n; n = n->next; // Otherwise, move to // next node } return NULL; // If you get here, data // wasn't found 5/19/2018 ECE Application Programming: Lecture 11

ECE Application Programming: Lecture 11 Final notes Next time Exam 3 Announcements/reminders Program 9 due today Exam 3 Thursday, 8/15 5/19/2018 ECE Application Programming: Lecture 11