In C, a pointer is a variable that stores the memory address of another variable. Pointers allow for more advanced memory manipulation and efficient program execution.
Address in C
In C, an address refers to the location of a variable or a function in memory. The address of a variable or function can be obtained by using the & (ampersand) operator.
For example, consider the following C code:
int x = 5; printf("The address of x is: %p", &x);
%p format specifier is used to print the address of
x. The output of this code will be something like:
The address of x is: 0x7ffcc045f8ac
This is the hexadecimal representation of the memory address where the variable
x is stored.
You can also use pointers to store and manipulate addresses in C. For example:
int x = 5; int *ptr = &x; printf("The value of ptr is: %p", ptr);
This code declares a pointer variable
ptr and assigns the address of
x to it. The
%p format specifier is used to print the value of the pointer variable
ptr, which will be the address of
Note that the address of a variable can change during program execution due to factors such as memory allocation and deallocation. Therefore, it is important to always use the correct address when accessing or manipulating variables using pointers.
To declare a pointer in C, you use the * symbol:
This declares a pointer variable named
ptr that can point to an integer value.
To assign a memory address to a pointer, you use the
int x = 5; int *ptr = &x;
This assigns the memory address of the variable
x to the pointer variable
To access the value at the memory address pointed to by a pointer, you use the * symbol:
int x = 5; int *ptr = &x; printf("%d", *ptr); // Output: 5
This prints the value of the variable
x using the pointer variable
You can also use pointers for dynamic memory allocation using the
int *ptr = malloc(sizeof(int));
This allocates memory for an integer value and assigns the memory address to the pointer variable
Remember to always properly manage memory when using pointers to avoid memory leaks and segmentation faults.