Mastering C Textbook
Everything On Pointers
Pointers in C are variables that hold the memory address of another variable. They enable indirect access to data by "pointing" to the data's location in memory.
Using A Pointer With Stack Memory
To declare a pointer, specify the data type followed by *. Here’s an example where we create an integer x and use a pointer to access its value indirectly
#include <stdio.h>
int main() {
int x = 10;
int *ptr; // Declare a pointer
ptr = &x; // Store the address of x in ptr
printf("Value of x: %d\n", x);
printf("Value through pointer: %d\n", *ptr); // Indirectly access x
return 0;
}OUTPUT:
Value of x: 10
Value through pointer: 10
Pointers With Heap Memory
You can use malloc to dynamically allocate memory to a pointer. In the following example we use sizeof with an integer to make a pointer with enough memory to store one integer.
Later you can use free to deallocate the memory you assigned in your program. This is important so you avoid memory leaks in your system. A
A memory leak occurs when you allocates memory dynamically but fails to release it after it's no longer needed. This unfreed memory remains reserved by the program, even though it’s no longer in use. Over time, memory leaks can cause a program to consume more and more memory, eventually slowing down the system or causing it to run out of memory, leading to crashes.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int)); // Allocate memory for an integer
*ptr = 20; // Assign value to allocated memory
printf("Value through pointer: %d\n", *ptr);
free(ptr); // Free allocated memory
return 0;
}OUTPUT:
Value through pointer: 20Compiling C With Command Line
You can compile and run your C code from the command line using the gcc tool, which turns your source code into an executable file. Here’s how to do it:
gcc -g -o myProgram main.cHere’s what each part of the command does:
gccis the tool that compiles your code.-gis an optional flag that adds debugging information to the complied program. This extra information allows debugging tools likevalgrind(see next section)-ois an optional flag that lets you specify the name of your executable. In this case, we named itmyProgram.main.cis your source code file. You can list multiple .c files if your program has more than one.
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 11 more lessons in Mastering C Textbook.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.