CSE 333 Section BB
Logistics Due Friday: Exercise 4 @ 11 am NO SCHOOL MONDAY Due Wednesday: Exercise 5 @ 11 am Exercise 6@ 11 am Due in 1 Week: (1/23) HW1 @11:59 pm
Defining Structs
Defining Structs
Defining Structs Similar syntax to: int x, *y;
Struct Memory diagrams
Fruits & Orchards
main bt name "Apple Orchard\0" origin apple volume applePtr console output 8
eatFruit main bt name "Apple Orchard\0" "Eaten Fruit Orchard\0" origin apple volume origin apple volume applePtr console output 9
main bt name "Apple Orchard\0" "Eaten Fruit Orchard\0" origin apple growFruit volume fruitPtr applePtr console output 10
main bt name "Apple Orchard\0" "Eaten Fruit Orchard\0" origin apple exchangeFruit volume fruitPtrPtr banana applePtr console output Heap Allocated Memory origin volume 12 name "Banana Orchard" 11
eatFruit main bt name "Apple Orchard\0" "Eaten Fruit Orchard\0" origin apple volume origin apple exchangeFruit growFruit volume fruitPtrPtr fruitPtr banana applePtr console output Heap Allocated Memory origin volume 12 name "Banana Orchard" 12
Valgrind ● ○ ./leaky 1 10 ● valgrind --leak-check=full ./leaky 1 10”
int main( int argc, char *argv[]) { if (argc != 3) return EXIT_FAILURE ; int * rangeArray( int n, int m) { int length = m - n + 1; // Parse cmd-line args int n = atoi(argv[1]), m = atoi(argv[2]); // Heap allocate the array needed to return int *array = ( int *)malloc( sizeof ( int ) * length); int *nums = rangeArray(n, m); // Initialize the elements // Print the resulting array for ( int i = 0; i <= length; i++) { for ( int i = 0; i <= (m - n + 1); i++) { array[i] = i + n; printf("%d", nums[i]); } } return array; // Append newline char to our output } puts(""); return EXIT_SUCCESS ; } 14
int main( int argc, char *argv[]) { if (argc != 3) return EXIT_FAILURE ; int * rangeArray( int n, int m) { int length = m - n + 1; // Parse cmd-line args int n = atoi(argv[1]), m = atoi(argv[2]); // Heap allocate the array needed to return int *array = ( int *)malloc( sizeof ( int ) * length); int *nums = rangeArray(n, m); // Initialize the elements // Print the resulting array // By using <=, we are writing to length + 1 // We’re allocating space for 10 ints, but we access // ints instead of length ints // 11 ints with i <= instead of i < // Change <= to < to fix this off-by-one error for ( int i = 0; i < (m - n + 1); i++) { for ( int i = 0; i < length; i++) { printf("%d", nums[i]); array[i] = i + n; } } return array; // We need to free the array of integers } // malloced in rangeArray. free(nums); // Append newline char to our output puts(""); return EXIT_SUCCESS ; } 15
Recommend
More recommend