1 Answer
1
answers
What is a pointer in C?
0
Answer link
In C, a pointer is a variable that stores the memory address of another variable. It "points" to the location in memory where a value is stored rather than storing the value directly.
Here's a breakdown of key aspects:
- Declaration: Pointers are declared using an asterisk (
*
) before the variable name. The type declaration specifies the type of data the pointer will point to. For example:int *ptr;
declares a pointer named 'ptr' that can store the address of an integer variable. - Address-of Operator: The
&
operator (address-of operator) is used to get the memory address of a variable. For example:int x = 10; ptr = &x;
assigns the address of 'x' to the pointer 'ptr'. - Dereference Operator: The
*
operator (dereference operator) is used to access the value stored at the memory address held by the pointer. For example:int value = *ptr;
retrieves the value stored at the address pointed to by 'ptr' (which is the value of 'x', i.e., 10) and assigns it to 'value'. - Uses:
- Dynamic memory allocation (using functions like
malloc
andcalloc
). GeeksForGeeks - Passing arguments by reference to functions. This allows functions to modify the original variables passed to them. TutorialsPoint
- Working with arrays and strings. Pointers can be used to efficiently iterate through arrays. TutorialsPoint
- Creating data structures like linked lists, trees, and graphs.
Example:
#include <stdio.h>
int main() {
int x = 10;
int *ptr;
ptr = &x; // ptr now holds the address of x
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", &x);
printf("Value of ptr: %p\n", ptr); // ptr stores the address of x
printf("Value pointed to by ptr: %d\n", *ptr); // Dereferencing ptr to get the value of x
*ptr = 20; // Modifying the value at the address pointed to by ptr (which is x)
printf("New value of x: %d\n", x); // x is now 20
return 0;
}
In this example, changing the value through the pointer ptr
also changes the value of the original variable x
because they both refer to the same memory location.