Pointer एक variable है जो किसी अन्य variable का adress store करता है (रखता है)| जिस प्रकार से हम variable की values में बदलाव कर पाते है , उसी प्रकार से हम pointer variable की value में बदलाव कर सकते है।
- Pointer में address स्टोर करने के लिए & (operator) उपयोग किया जाता है। इसे address of operator कहते है।
- जिस variable address पर pointer पॉइंट कर रहा है , उस पर जो value है उसको access करने के लिए *(asterisk operator) का उपयोग करते है। इसे dereference operator कहते है।
- यदि हम pointer की मदद से value change करेंगे तो variable की भी value change हो जाएगी जिसको pointer variable point कर रहा था।
- जिस data type का pointer variable होगा वह उसी type के किसी दुसरे variable का एड्रेस store कर सकता है।
#include <stdio.h>
// syntax
// data_type *variable = &variable;
int main() {
int a = 10;
// ptr ---> a
int *ptr = &a;
// accessing value through pointer & variable
// using pointer
printf("*ptr = %dn", *ptr); // 10;
printf("a = %dn", a); // 10
// changing value using pointer
*ptr = 15;
printf("After changing valuen");
printf("*ptr = %dn", *ptr); // 15;
printf("a = %dn", a); // 15
return 0;
}
// output
// *ptr = 10
// a = 10
// After changing value
// *ptr = 15
// a = 15}
दिया गए उदाहरण में a एक variable है एवं *ptr एक pointer (pointer variable) है, जिसमे variable a address assign कर दिया है।
void type का poitner किसी भी प्रकार(data type) के address को स्टोर कर सकता है।
Types of pointers
- Void Pointer
- NULL Pointer
- Dangling Pointer
- Wild Pointer
1. Void Pointer
Void pointer एक प्रकार का pointer है, void प्रकार का pointer किसी भी प्रकार के pointer में type cast हो जाता है।
#include <stdio.h>
int main() {
// void pointer
void *ptr;
return 0;
}
2. Null Pointer
NULL pointer एक प्रकार का पॉइंटर है, वह pointer जिसमे हमने NULL assign कर दिया है वह NULL pointer कहलाता है।
#include <stdio.h>
int main() {
int *ptr = NULL; // null pointer
return 0;
}
3. Dangling Pointer
Dangling एक प्रकार का pointer है, जो की उस memory location या address को पॉइंट करता है जो पहले delete या free कर दी गयी हो।
#include <stdio.h>
#include <stdlib.h>
int main() {
// dynamic memory allocation
int *ptr = (int* ) malloc(sizeof(int));
// free memory
free(ptr);
// ptr is pointing to a deleted memory location now.
// now ptr became dangling pointer
// garwage value displayed
printf("value of *ptr is %d ", *ptr);
return 0;
}
4. Wild Pointer
Wild pointer एक प्रकार का pointer है, जो की declare तो किया गया है लेकिन कोई भी address नहीं दिया है।
#include <stdio.h>
int main() {
// wild pointer
int *ptr;
printf("%dn", *ptr);
return 0;
}