cs31 lecture 9

The type of the pointer used void is an address but

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: caution Typical pitfall: segmentation fault For best programming style, cast the output of malloc with the type of the pointer used void* is an address, but cannot be dereferenced 16 Dynamic allocation in C++ New: operator equivalent to malloc Different syntax: int* a = new int[10]; Delete: operator equivalent to free Different syntax: delete a; 17 Examples 18 Multidimensional arrays Case 1: a multidimensional array is a 1-d array with multiple ways to index it Think about a 2-d array being flattened Case 2: a multidimensional array is an array of array Think about an array storing addresses of 1-d arrays Example: int a[10][10]; // a contiguous region of 100 elements in memory 19 Case 1 vs. Case 2 Different address computation Similar C references Nested Array int get_univ_digit Multi-Level Array int get_pgh_digit (int index, int dig){ (int index, int dig){ return pgh[index][dig]; return univ[index][dig]; } } Element at Element at Mem[pgh+20*index+4* dig] Mem[Mem[univ+4*index] +4*dig] cmu univ 1 5 2 0 6 1 5 2 1 3 1 5 2 1 7 1 5 2 2 1 76 96 116 136 156 160 36 164 16 168 56 mit 1 16 5 20 0 ucb 36 56 2 24 2 40 9 28 1 44 4 60 1 32 3 48 7 64 3 52 2 68 36 9 56 0 72 76 20 Examples 21 Summary on arrays Arrays are key to real data manipulation Now, you can start implementing your data structures! Stack List Graph (using adjacency matrix representation) … When the array needs to live after a function has finished, use dynamic allocation In other cases, use static allocation, and 22 Summary on arrays Statically allocated arrays (eg, int a[10]) CANNOT be changed after the declaration (increase/decrease size) Dynamically allocated arrays (eg, with malloc()) CAN be changed after the declaration, BUT needs to be freed In all cases, you CANNOT know the size of an array apart from where it is declared/allocated 23...
View Full Document

This note was uploaded on 04/03/2014 for the course CS 31 taught by Professor Melkanoff during the Fall '00 term at UCLA.

Ask a homework question - tutors are online