Master C Pointers: Definition, Usage, and Practical Examples
This article explains what pointers are in the C language, how to define and use them, common scenarios such as dynamic memory allocation and array handling, and provides a complete, annotated example that demonstrates accessing and modifying variable values through pointers.
What is a pointer in C?
A pointer is a variable that stores the memory address of another variable, allowing direct access and manipulation of the data stored at that address.
How to use pointers
Define a pointer : Use the * operator in the declaration, e.g., int *p; creates a pointer to an int.
Obtain an address : Use the address‑of operator & to get a variable’s address, e.g., p = &a; assigns the address of a to p.
Access or modify the pointed value : Dereference the pointer with * to read or write the value at that address, e.g., *p = 10; stores 10 at the location pointed to by p.
Typical use cases
Dynamic memory allocation : Functions such as malloc and free allocate and release memory at runtime.
Array and string manipulation : Pointers can traverse and modify arrays or strings efficiently.
Function parameter passing : Large structures (arrays, structs) are often passed by pointer to avoid copying overhead.
Complete example
The program below demonstrates defining a pointer, obtaining a variable’s address, accessing the value through the pointer, and modifying the original variable via the pointer.
#include <stdio.h>
int main() {
int a = 100;
int *p; // define a pointer to int
p = &a; // obtain the address of a
printf("Value of a: %d
", a);
printf("Address of a: %p
", (void*)&a);
printf("Pointer p value (address of a): %p
", (void*)p);
printf("Value accessed via pointer p: %d
", *p);
*p = 200; // modify a through the pointer
printf("Modified value of a: %d
", a);
return 0;
}This example prints the original value and address of a, shows the pointer’s stored address, accesses the value via *p, changes the value to 200 through the pointer, and prints the updated value.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
