Theory
નકારાયેલી line શોધો
Riya નો સરવાળાનો loop, array પર ચાલવા માટે array નું નામ જ વાપરે છે:
int marks[5] = {70, 55, 90, 62, 78}, total = 0;
total += *marks;
marks++;
કઈ line compile નહીં થાય?
Think first
પહેલાં તમારો અંદાજ
Line અને એનું કારણ type કરો.
Show the answer
marks++. Array નું નામ એક constant address છે: box zero પર રોપેલો signpost, અને signposts ખસતા નથી. *marks બરાબર છે: એનો અર્થ marks[0] છે, એટલે કે 70. Address ને p માં copy કરો: p++ legal છે.
Theory
નામ એટલે address
marks લખવાથી &marks[0] મળે છે, એટલે કે base address, તેથી int *p = &marks[0]; ટૂંકમાં int *p = marks; બને છે, & વગર. C, marks[i] ને *(marks + i) તરીકે define કરે છે (i boxes આગળ ચાલો, પછી box ખોલો), એટલે *(p + i) અને p[i] પણ એ જ box સુધી પહોંચે છે.
Think first
કયા 90 આપે છે?
p = marks હોય ત્યારે આ દરેકની value શોધો: marks[2], *(marks + 2), *(p + 2), p[2], *p + 2.
Show the answer
પહેલા 4 expressions box 2 વાંચે છે: 90. *p + 2 એ 72 છે: * પહેલાં 70 વાંચે છે, પછી 2 ઉમેરાય છે.
Quiz
name એક char array હોય ત્યારે scanf("%s", name) ને & ની જરૂર કેમ નથી?
- name પહેલેથી જ name[0] નું address છે
- %s ના કારણે scanf જાતે & ઉમેરી દે છે
- Strings scanf પાસે value તરીકે જાય છે, address તરીકે નહીં
- Compilers ખૂટતા & ને ચૂપચાપ માફ કરી દે છે
Show the answer
name પહેલેથી જ name[0] નું address છે
name નો અર્થ પહેલેથી જ &name[0] છે, એટલે કે લખવાની જગ્યા; સાદા int નું નામ ફક્ત એની value આપે છે. કંઈ ઉમેરાતું નથી, અને કંઈ માફ પણ થતું નથી.
Think first
Size સરખો?
p અને marks બંને &marks[0] આપે છે. શું sizeof(p) અને sizeof(marks) સરખા આવે છે?
Show the answer
ના. sizeof(marks) આખા array નો size આપે છે, int 4 bytes નો હોય ત્યારે 5 × 4 = 20 bytes; sizeof(p) એક pointer નો size આપે છે, સામાન્ય રીતે 4 કે 8 bytes. Functions ને marks ફક્ત એક address તરીકે મળે છે (pass by reference, Unit 4).
Practical
Exam-style: output કહો
#include <stdio.h>
int main() {
int marks[5] = {70, 55, 90, 62, 78};
int *p = marks;
int i, total = 0;
for (i = 0; i < 3; i++) {
total += *p;
p++;
}
printf("%d %d", total, p[1]);
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 શું છે?
- 215 78
- 215 62
- 215 55
- Program compile થતો નથી
Show the answer
215 78
Pointer પર p++ legal છે. 3 rounds માં 70 + 55 + 90 = 215 ઉમેરાય છે અને p, marks[3] પર પહોંચી જાય છે; p[1] ત્યાંથી ગણે છે: marks[4], એટલે 78. છેલ્લો p++ ભૂલી જવાથી 62 મળે છે; p[1] ને marks[0] થી ગણવાથી 55 મળે છે.
Summary
Key takeaways
- marks લખવાથી &marks[0] મળે છે, એટલે int *p = marks; માં & ની જરૂર નથી.
marks[i]એટલે*(marks + i);p[i]એટલે*(p + i), p જ્યાં ઊભો છે ત્યાંથી ગણીને.- p++ legal છે, marks++ નહીં; sizeof(marks) આખા array નો size આપે છે.
- યાદ રાખવાની યુક્તિ: નામ એક રોપેલો signpost છે, અને signposts ખસતા નથી.