Intermediate Pointers and Basic Structures: A Review, Study notes of C programming

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

2021/2022

Uploaded on 09/27/2022

stifler
stifler ๐Ÿ‡ฎ๐Ÿ‡น

4

(7)

215 documents

1 / 18

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
C Lab 2
Intermediate Pointers & Basic Structures
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download Intermediate Pointers and Basic Structures: A Review and more Study notes C programming in PDF only on Docsity!

C Lab 2

Intermediate Pointers & Basic Structures

Goals

โ— Review โ—‹ Pointers โ—‹ Referencing/Dereferencing โ—‹ free โ— realloc โ— structs โ— ArrayList

Getting Pointer/Reference

โ— 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

Pass by copy: void plus(int num){ num++; }

void main(){ int num = 3; plus(num); printf(โ€œ%d\nโ€, num); } What does main print?

Void * and realloc

โ— โ€œ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

Realloc and Equivalent

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

Structs

typedef struct arraylist { int *buffer; int buffersize; int length; } arraylist;

Editing Struct Fields

โ— You may declare structs on the stack

โ— You may access/edit fields of struct using โ€˜.โ€™

โ— Think about why this works (Hint: pointers)

Editing Struct Fields

โ— You may declare structs on the heap

โ— Now you access/edit fields using โ€˜->โ€™

โ— This syntax is more helpful visually

Editing Struct Fields

arraylist *a = (arraylist *)malloc(sizeof(arraylist)); a->buffer = NULL; a->buffer_size = 0; a->length = 0;

Memory Management

โ— 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

Memory Takeaways

โ— 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-