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.
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; |
Example
Let us now see an example is to create a pointer variable and point to an integer variable:
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 = %p",&a); printf("\nThe memory address of the variable %p",&a); printf("\nThe memory address of the variable a with the pointer = %p",b); return 0; } |
Output
1 2 3 4 5 |
Integer Value = 0x7ffcfc4e1d34 The memory address of the variable 0x7ffcfc4e1d34 The memory address of the variable a with the pointer = 0x7ffcfc4e1d34 |
No Comments