Hello and welcome to CS50!
We’re onto the fourth week of C! This week we will be learning about memory in C. Memory is a fundamental concept in computer science, and understanding how it works is essential for writing efficient and reliable programs. This week we will be learning about pointers, dynamic memory allocation, and how to work with images in C.
Pointers are a powerful feature of C that allow you to work directly with memory addresses. They can be used to create complex data structures, such as linked lists and trees, and to optimize the performance of your programs. This week we will be learning how to declare, initialize, and use pointers, as well as how to avoid common pitfalls when working with them.
Dynamic memory allocation is a technique that allows you to allocate memory at runtime, rather than at compile time. This can be useful for creating data structures of unknown size, such as arrays and linked lists, and for optimizing the memory usage of your programs. This week we will be learning how to use malloc
, calloc
, and free
to allocate and deallocate memory, as well as how to avoid memory leaks and other memory-related bugs.
Finally, we will be learning how to work with images in C. Images are a common type of data that are used in many different applications, from web browsers to video games. This week we will be learning how to read and write images in C, as well as how to manipulate them using various image processing techniques.
Resources:
Section-Specific:
- Sections are held Thursdays 9AM-11:45AM in 2 Arrow St. Room 420
- Section Slides
Course-wide:
- Week 4 Lecture Notes
- Week 4 Lecture Slides
- Problem Set 4: Arrays Due Sunday, Oct 6, 2024 11:59PM
- Syllabus
- Course FAQs
- Previous Year’s Feedback/Advice
Office Hours:
- My Office Hours: Friday 10:30AM-11:30AM in HSA Building 4th Floor
- All-Staff Office Hours: Sunday 3-5PM in Widener Library
- Office Hours Schedule
- Add this Google Calendar
- If you have any questions at all, email me!
Common Patterns for the Problem Set
Swap two variables
// we want to swap a, b
int a = 1;
int b = 2;
// we use a temporary variable to do so
int tmp = a;
a = b;
b = tmp;
File I/O
Open a file (in “read” mode) — to read its content
FILE *f = fopen(filename, "r");
Open a file (in “write” mode) — to write into it
FILE *f = fopen(filename, "w");
Read file data into a buffer
fread(buffer, 1, BLOCK_SIZE, file);
Write file data from a buffer
fwrite(buffer, 1, BLOCK_SIZE, img);