A Pointer is a special variable that stores the memory address of another variable. Instead of holding a direct value like an integer or a character, a pointer "points" to the location where a value is stored in the computer's memory.
[Image of pointer variable pointing to a memory address of another variable]A pointer must be declared with a data type that matches the type of the variable it points to. This is because the compiler needs to know how many bytes of memory to read when accessing the value at that address.
data_type *pointer_name;
Example:
int *p; - A pointer to an integer variable.float *fptr; - A pointer to a floating-point variable.char *ch; - A pointer to a character variable.Initialization is the process of assigning a memory address to a pointer variable. This is done using the Address-of Operator (&).
int num = 10;
int *ptr; // Declaration
ptr = # // Initialization (ptr now stores the address of num)
Warning: Always initialize pointers. A pointer that is declared but not initialized is called a Wild Pointer and contains a random memory address, which can lead to system crashes.
You can access the actual value stored at the memory address held by a pointer using the Dereferencing Operator (*), also known as the Indirection Operator.
int x = 25;
int *p = &x;
printf("Value of x: %d", *p); // Output: 25
In the above code, *p tells the computer to "go to the address stored in p and get the value located there."
Pointer arithmetic allows you to perform addition and subtraction on pointers. However, unlike regular math, pointer arithmetic is based on the size of the data type it points to.
int pointer on a 4-byte system, it adds 4 to the address.n * sizeof(data_type) to the address.n * sizeof(data_type) from the address.Formula for Addition:
New_Address = Current_Address + (n * Size_of_Data_Type)
Beyond basic arithmetic, several other operations can be performed on pointers:
*. In declaration (int *p), it means "pointer." In execution (*p = 10), it means "value at address."NULL (e.g., int *ptr = NULL;). This is a safe practice.int **pp;. This is a pointer that stores the address of another pointer.*p) a pointer before giving it an address.float address to an int pointer without explicit typecasting.&10 is invalid).Q: What is the size of a pointer variable?
A: The size of a pointer is independent of the data type it points to. It depends on the architecture of the computer (usually 4 bytes on a 32-bit system and 8 bytes on a 64-bit system).
Q: Why do we use pointers?
A: Pointers allow for efficient handling of arrays, dynamic memory allocation, and the ability to return multiple values from a function via call-by-reference.
Q: Can we add two pointers together?
A: No. Adding two memory addresses is logically meaningless and prohibited in C.