120 likes | 161 Views
Learn to manage dynamic data efficiently in C programming using pointers and dynamic memory allocation techniques. Explore best practices and avoid common pitfalls!
E N D
Dynamic Data • Suppose we write a program to keep track of a list of students • How many student records should we create? • What if we create too few? • What if we create too many? • Wouldn’t it be nice to create just as many as we need?!
Pointer Review • What is a pointer? • How does one declare a pointer variable? • If all pointers store an address, why must a data type be associated with a pointer? • What values are associated with a pointer? • When using indirection, what steps are followed to get the specified value *ptr in the ex. below? ie) int *ptr, x, y = 5; ptr = &y; x = *ptr;
Pointers to Structures • Declare a pointer to a structure of type inventory_item
Pointers to Structures • Declare a pointer to a structure of type inventory_item inventory_item *shirts; • Store 1234 in the id field
Pointers to Structures • Declare a pointer to a structure of type inventory_item inventory_item *shirts; • Store 1234 in the id member field (*shirts).id = 1234;
Pointers to Structures • Declare a pointer to a structure of type inventory_item inventory_item *shirts; • Store 1234 in the id member field (*shirts).id = 1234; shirts->id = 1234;
Dynamic Memory Allocation • Stack: Area where function data is allocated and reclaimed as program executed • Heap: Area C sets aside assuming that the programmer will ask for more memory as program executes
Dynamic Memory Allocation malloc(…) • allocate a chunk of memory large enough to store an int • returns first address of location reserved – need to cast address to a valid type malloc(5) malloc(sizeof(int)) malloc(sizeof(struct_type)) malloc(10*sizeof(int)) free(var_name) • free up the memory pointed to by var_name
Examples int *int_ptr; int_ptr = (int*)malloc(sizeof(int)); inventory_item *shirts;
Examples int *int_ptr; int_ptr = (int*)malloc(sizeof(int)); inventory_item *shirts; shirts = (inventory_item*)malloc(sizeof(inventory_item); (*shirts).id = 1234; shirts->cost = 20.00;
Examples int *int_ptr; int_ptr = (int*)malloc(sizeof(int)); inventory_item *shirts; shirts = (inventory_item*)malloc(sizeof(inventory_item); (*shirts).id = 1234; shirts->cost = 20.00; free(int_ptr); free(shirts);