










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A review of pointers, referencing and dereferencing, memory allocation functions realloc and free, and structs. Topics covered include understanding pointers as memory addresses, getting pointers using '&' and dereferencing using '*.' The document also covers pass by copy and pass by reference, void * and realloc, and structs as personalized types. Memory management best practices are also discussed.
Typology: Study notes
1 / 18
This page cannot be seen from the preview
Don't miss anything!











Intermediate Pointers & Basic Structures
โ Review โ Pointers โ Referencing/Dereferencing โ free โ realloc โ structs โ ArrayList
โ To get pointer to something, use โ&โ
โ โ&โ allows to pass items by reference
โ To dereference or get item pointed to use โ*โ
โ โ*โ is the opposite of โ&โ
Pass by copy: void plus(int num){ num++; }
void main(){ int num = 3; plus(num); printf(โ%d\nโ, num); } What does main print?
โ โvoid โ may point to arbitrary types (i.e. int, char*, etc.)
โ Can be casted to appropriate types
โ realloc increases the size of memory allotted to pointer
โ Preserves data pointed to by original pointer
โ Original pointer is NULL, if space is found elsewhere
ptr = malloc(2); ptr = realloc(ptr, 1000);
ptr = malloc(2); ptr2 = malloc(1000); memcpy(ptr2, ptr, 2); free(ptr); ptr = ptr2; ptr2 = NULL;
Why not: ptr = malloc(2); realloc(ptr, 1000);
typedef struct arraylist { int *buffer; int buffersize; int length; } arraylist;
โ You may declare structs on the stack
โ You may access/edit fields of struct using โ.โ
โ Think about why this works (Hint: pointers)
โ You may declare structs on the heap
โ Now you access/edit fields using โ->โ
โ This syntax is more helpful visually
arraylist *a = (arraylist *)malloc(sizeof(arraylist)); a->buffer = NULL; a->buffer_size = 0; a->length = 0;
โ Do not free what you did not malloc!!! โ Do not free address consecutively!!!
int num = 3; free(&num); // :,O
int *num = malloc(4) free(num); //yaaaayyy free(num); //staaahp
โ Only free what has been mallocโd
โ Only free mallocโd memory once
โ For more on stack vs. heap: http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html#sec-