Зміст курсу
C Basics
C Basics
Pointers are around Us
You're probably already familiar with the idea of pointers from your everyday experiences. Think about how your house has a unique address. It's through this address that you receive Amazon packages, letters, and that pizza you just ordered. Essentially, to reach you, people and services use your home address.
When a house changes hands, it's essential to update the records to reflect the new owner's details. And if your family grows, it's crucial to add the new members to the address's associated records.
The property ownership records are constantly being updated. Some data is modified, some is deleted, while new details are added.
Let's consider another example - developing a security system for your office. The developer might not know the exact number of employees you'll have. So, in the code, they might allocate space for 100 employees:
This setup is quite basic and inherently limited from the get-go.
But what if your company expands, launching a new department, and recruits 30 new skilled employees, bringing the total to 130? However, the security system is only set up to recognize 100. Do you overhaul the entire security setup or let the new hires go? This dilemma is addressed through dynamic memory allocation.
Dynamic Memory Allocation
In the C language, there are three types of memory allocation:
- Static allocation, which happens at compile time. For instance, when the compiler sees you've declared an
int
variable, it allocates 4 bytes for it; - Automatic memory allocation takes place within functions, particularly when variables are declared inside these functions;
- Dynamic memory allocation stands out because memory is assigned not at the compilation stage but during the actual running of your program.
Dynamic memory allocation gives the programmer full control, as they oversee both the allocation and deallocation of memory. This approach allows a programmer to significantly optimize the performance of a program, with pointers playing a pivotal role in this process.
Дякуємо за ваш відгук!