Theory
कौन-सा ख़तरनाक है?
3 pointers:
int *a = &marks;
int *b = NULL;
int *c;
c को कभी कोई value नहीं मिलती। किसे dereference करना सबसे ख़तरनाक है?
Think first
पहले आपका अंदाज़ा
Letter और अपनी वजह type कीजिए।
Show the answer
c। उसमें पुराना garbage पड़ा है, इसलिए *c किसी अनजान जगह को छूता है; c एक wild pointer है। *b भी एक error है, पर if (b != NULL) से पहले जाँचा जा सकता है। हर pointer को initialize कीजिए, किसी target से या NULL से।
Theory
हर type का अपना pointer
int *pi = &marks;, float *pf = &perc; और char *pc = &grade; तीनों अपने target से मेल खाते हैं। Type इसलिए ज़रूरी है कि dereference उसी से जानता है कि कितने bytes पढ़ने हैं और कैसे पढ़ने हैं: int के रूप में आम तौर पर 4 bytes, char के रूप में 1 byte।
Practical
Pointer drill
#include <stdio.h>
int main() {
int marks = 78;
float perc = 78.5;
char grade = 'A';
int *pi = &marks;
float *pf = &perc;
char *pc = &grade;
printf("%d %.1f %c", *pi, *pf, *pc);
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
Float के pointer को int * की जगह float * क्यों declare करना पड़ता है?
- Type से * जानता है कि कितने bytes और कैसे पढ़ने हैं
- यह सिर्फ़ नाम रखने का तरीका है
- Float pointers memory के एक अलग, ख़ास हिस्से में रखे जाते हैं
- int pointer बड़ा address नहीं रख सकता
Show the answer
Type से * जानता है कि कितने bytes और कैसे पढ़ने हैं
हर pointer एक address रखता है; type, * को बताता है कि उसे कैसे पढ़ना है। ग़लत type सही जगह को ग़लत तरीके से पढ़ता है: garbage।
Theory
NULL और void *
NULL का मतलब है "अभी कहीं point नहीं करता", और code इसे जाँच सकता है। void *vp, यानी generic pointer, किसी भी type का address रख सकता है, पर cast किए बिना उसे dereference नहीं किया जा सकता: *(int *)vp।
Think first
Pointers गिनिए
int* a, b; कितने pointers declare करता है?
Show the answer
एक: a pointer है, पर b सिर्फ़ एक int है। * नाम के साथ जुड़ता है, type के साथ नहीं, इसलिए 2 pointers के लिए int *a, *b; लिखिए।
Practical
Exam-style: output बताइए
#include <stdio.h>
int main() {
int x = 7;
void *vp = &x;
int *ip = (int *)vp;
*ip = *ip + 3;
printf("%d %d", x, *(int *)vp);
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
Exam-style: ऊपर वाले program का output क्या है?
- 10 10
- 7 10
- 10 7
- Compile error
Show the answer
10 10
vp और ip दोनों में x का address है। ip के ज़रिए 3 जोड़ने से x 10 हो जाता है, और *(int *)vp उसी box को पढ़ता है।
Summary
Key takeaways
- Pointer का type target से मिलाइए:
int *,float *,char *। - हर pointer को initialize कीजिए, target से या NULL से; उसे wild मत छोड़िए।
void *कोई भी address रखता है, पर*से पहले cast चाहिए।- याद रखने का hook: खाली पर्ची, किसी random address वाली पर्ची से बेहतर है।