130 likes | 217 Views
Recitation March 27, 2014. Project 2 Due on Monday! Email me soon if you need help! Project 3 will be going out sometime next week We’ll review it in class next Thursday. . Announcements. Declaring new structs : 3 basic components: Unique name Variable names Variable types Example :
E N D
Project 2 Due on Monday! • Email me soon if you need help! • Project 3 will be going out sometime next week • We’ll review it in class next Thursday. Announcements
Declaring new structs: • 3 basic components: • Unique name • Variable names • Variable types Example: typedefstructplayer_info_{ charinitials[3]; intheight; floatavg_points; } player_info, *p_player_info; Structs
To access each piece of data, use a ‘.’ Dixon.height=68; Dixon.initials[0]=‘J’; • Pointers to structs work the same way as normals pointers. To declare them: player_info *Allen Structs
To access information from pointers you need to dereference the pointer first: a=*(Dixon).height; Why does it make sense that the pointer has to be dereferenced first? • Short cut! Use ‘->’ to dereference the pointer and access a data field at the same time. a=Dixon->height; Struct Pointers
Pointer arithmetic is also the same when using structs: inti=0; temp=team; for(i=0;i<5;i++) { temp->height=60+3*i; temp++; } • Be aware that pointer arithmetic with the data elements will be based on the size of the data type of each element. Struct Pointers
Used to manage memory at a low(ish) level • Important functions: • Malloc • Calloc • Realloc • Free Dynamic Memory Allocation
Basics to remember: • Casting • Sizeof • Reassignment p_player_info Blake; char *a, *array[10]; a=(char *) malloc(sizeof(char)); For(i=0;i<10;i++) { array[i]=(char *)malloc(sizeof(char)*n[i]); } Malloc
Very similar to malloc, it is more explicit when it comes to allocating space for arrays: a=calloc(10,sizeof(char)); This is the same as: a=malloc(sizeof(char)*10); Calloc
Reallocates memory space for an existing pointer. a=(char *)realloc(a,sizeof(char)*10); • Realloc only returns a pointer if the request can be carried out- be sure to check that it worked! Realloc
Create a struct • In the “main” function, define two pointers to the new struct type that you created. Hint! Blake=(p_player_info)malloc(sizeof(player_info); • Use malloc to allocate memory for one • Use calloc to allocate memory for the other • Use realloc in a for loop to resize the first pointer at least 5 times. • Submit using ‘5’ Coding example
Create an array of pointers to integers • Use a for loop and malloc to allocate memory space for each pointer • Create a “cleanup” function • Free all of the memory space allocated in the program. • Add it to your code Coding Example