In this lesson, you will learn about pointers in C Programming, and their usage, along with examples to better understand the topic.
A Pointer is a strong attribute in C programming. It is a variable used to reserve the address of some other variable. The Pointer can be of any data type like int, float, etc.
The pointer concept can be a bit tricky to understand. The simplest form of pointers, for example, is a variable ‘a’ of int type in your program, and &a is the address of that variable in the memory.
datatype* pointer;
Pointer stores the address rather than values.
int* ptr;
In the above example, ptr is the Pointer of int type.
When assigning values to a pointer, use the reference variable & with it.
int* ptr; int mathMarks = 100; ptr = &mathMarks;
ptr will get the address of mathMarks variable so ptr holds now 100. If you want to print ptr value, use * with ptr. It is also called dereference operator.
int *ptr; int mathMarks = 100; ptr = &mathMarks; printf ("%d", *ptr);
// Example of pointer #include <stdio.h> int main () { int marks = 15; printf ("marks: %d\n", marks); // pointer &marks gives the address of variable marks in memory printf ("pointer of marks: %p", &marks); //%p is the format specifier of pointer return 0; }
Output
marks: 15 pointer of marks: 0x7ffd78e26af4
// Example of the pointer after assigning value to it #include <stdio.h> int main () { int *ptr; int marks = 15; printf ("Value of marks: %d\n", marks); ptr = &marks; // pointer &marks gives the address of variable marks in memory printf ("value of pointer of ptr: %d", *ptr); return 0; }
Output
Value of marks: 15 value of pointer of ptr: 15
You can change the value of Pointer by changing the variable value assigned to it. See the example below; marks initially assigned a value of 75. Pointer ptr holds the same address of marks after this statement
ptr = &marks;
In the next statement, marks have been changed to 100. As ptr has the same address of marks, so ptr value will become 100.
int *ptr, marks; marks = 75; ptr = &marks; marks = 100;
// Example of pointer after changing its value #include <stdio.h> int main () { int *ptr, marks; marks = 75; ptr = &marks; marks = 100; printf ("value of marks: %d\n", marks); printf ("value of pointer ptr: %d", *ptr); return 0; }
Output
value of marks: 100 value of pointer ptr: 100
In the next lesson, you will learn about memory management In C.