Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pointers and Dynamic Memory Allocation. Dynamic Data Suppose we write a program to keep track of a list of students How many student records should we.

Similar presentations


Presentation on theme: "Pointers and Dynamic Memory Allocation. Dynamic Data Suppose we write a program to keep track of a list of students How many student records should we."— Presentation transcript:

1 Pointers and Dynamic Memory Allocation

2 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?!

3 Pointer Review 1.What is a pointer? 2.How does one declare a pointer variable? 3.If all pointers store an address, why must a data type be associated with a pointer? 4.What values are associated with a pointer? 5.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;

4 Pointers to Structures Declare a pointer to a structure of type inventory_item

5 Pointers to Structures Declare a pointer to a structure of type inventory_item inventory_item *shirts; Store 1234 in the id field

6 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;

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

8 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

9 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

10 Examples int *int_ptr; int_ptr = (int*)malloc(sizeof(int)); inventory_item *shirts;

11 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;

12 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);


Download ppt "Pointers and Dynamic Memory Allocation. Dynamic Data Suppose we write a program to keep track of a list of students How many student records should we."

Similar presentations


Ads by Google