17 Jul C – Pointers
The C Pointer is a variable that is used to store the memory address as its value. However, to get the memory address of a variable, use the & operator. This means a variable has a unique memory location. This memory location has its own address. To access this address, we use the ampersand i.e., the & operator.
In this lesson, we will discuss the two operators useful to understand the concept of Pointers in C:
- The Address Operator: Access the address of a variable. Defined byĀ &, the ampersand sign.
- The Indirection Operator: Access the value of an address. Defined byĀ *, the asterisk sign.
Advantages of Pointers
- Efficiency: Direct access to memory and hardware improves performance.
- Dynamic Memory: They enable the dynamic allocation and deallocation of memory, avoiding wastage.
- Complex Data Structures: Pointers are fundamental for creating complex data structures like linked lists and trees.
- Function Pointers: These allow for callback functions and better modularity in code.
Disadvantages of Pointers
- Complexity: They can make the code more complex and harder to understand.
- Debugging Issues: Pointer-related bugs like segmentation faults and memory leaks are hard to debug.
- Security Risks: Incorrect usage can lead to vulnerabilities like buffer overflow.
- Memory Management: Manual memory management can be prone to errors, such as not freeing up memory, leading to memory leaks.
Let us see an example to display the address of variables in C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <stdio.h> int main() { int a; float b; char c; printf("Address of variable a = %p",&a); printf("\nAddress of variable b = %p",&b); printf("\nAddress of variable c = %p",&c); return 0; } |
Output
1 2 3 4 5 |
Address of variable a = 0x7fffb239b8a0 Address of variable b = 0x7fffb239b8a4 Address of variable c = 0x7fffb239b89f |
Syntax
1 2 3 |
dataType *varName; |
Above,Ā varNameĀ is the pointer variable, whereas datatype is the type.
Declare and create a Pointer
Follow the above syntax and let us see how we can create and declare pointers:
1 2 3 |
int* a; |
In C, both int *a; and int* a; are syntactically correct and do the same thing: they declare a pointer to an integer.
Example
Let us now see an example is to create a pointer variable and point to an integer variable. Here, TheĀ int* b declaresĀ bĀ as a pointer to an integer:
The int*b = &a means thatĀ bĀ is a pointer to an integer, and it is being initialized with the address of a.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <stdio.h> int main() { // Integer variable a int a = 10; // A pointer variable b storing the address of the variable a int* b = &a; printf("Integer Value = %d",a); printf("\nAddress of a (using &a) %p",&a); printf("\nAddress of a (using pointer b) = %p",b); return 0; } |
Output
1 2 3 4 5 |
Integer Value = 10 Address of a (using &a) 0x7ffcfc4e1d34 Address of a (using pointer b) = 0x7ffcfc4e1d34 |
No Comments