C Dereference Pointer
Syntax
*pointer
Example
#include<stdio.h>
int main()
{
int a = 5;
int *p = &a;
printf("Value of a: %d\n", a); // Output: Value of a: 5
printf("Value of *p: %d\n", *p); // Output: Value of *p: 5
printf("Address of a: %p\n", &a); // Output: Address of a: 0x7ffeec99ab12
printf("Value of p: %p\n", p); // Output: Value of p: 0x7ffeec99ab12
printf("Value of &p: %p\n", &p); // Output: Value of &p: 0x7ffeec99ab08
printf("Value of *&p: %p\n", *&p); // Output: Value of *&p: 0x7ffeec99ab12
return 0;
}
Output
Value of a: 5
Value of *p: 5
Address of a: 0x7ffeec99ab12
Value of p: 0x7ffeec99ab12
Value of &p: 0x7ffeec99ab08
Value of *&p: 0x7ffeec99ab12
Explanation
The dereference operator (*
) in C is used to access the value pointed to by a pointer variable. In the above example, p
is a pointer variable that points to the memory location of variable a
. The value of a
can be accessed by using the dereference operator *
with the pointer variable p
.
Use
The dereference operator allows C programmers to manipulate the value stored at a particular memory location through a pointer. This can be useful for several reasons, such as:
- Dynamic memory allocation: Pointers can be used to dynamically allocate memory during runtime, and the dereference operator can be used to access or modify the values stored in that memory.
- Passing pointers as function arguments: Pointers can be passed as arguments to functions, and the dereference operator can be used to access the values stored at the memory address pointed to by the pointer.
- Object-oriented programming: In C++, pointers and dereferencing are used to access members of objects dynamically allocated on the heap.
Important Points
- The dereference operator
*
is used to access the value stored at the memory location pointed to by a pointer variable. - A pointer variable must be initialized with an address before it can be dereferenced.
- Dereferencing a NULL pointer can cause the program to crash or produce undefined behavior.
Summary
In summary, the dereference operator *
is a powerful tool in C programming that allows programmers to access and manipulate the values stored at specific memory locations via a pointer. By understanding how to use this operator, programmers can take advantage of dynamic memory allocation, pass pointers as function arguments, and implement object-oriented programming concepts in C++.