C++ Arrays & pointers -
can me following inequalities arrays:
#include <stdio.h> #define prd(a) printf("%d", (a)) #define nl printf("\n") int a[] = {0,1,2,3,4}; int main () { int i; int*p; (i=0; i<=4; i++) prd(a[i]); nl; (p=&a[0]; p<=&a[4]; p++) prd(*p); nl; (p=&a[0]; i=0; p+i<=a+4; i++) prd(p[i]); nl; (p=a, i=0; p+i<=a+4; p++, i++) prd(*(p+i)); nl;
basically dont understand 4 loops, please kindly explain me!
a detail here, "inequalities" you're asking about pointers, not arrays. think of comparing memory locations, , following easier follow.
- first 1 should pretty straightforward: print each element of array in order (
a[0]
,a[1]
, etc.) - in number 2,
p
address of element0
ofa
.p++
increases address address of next element in array.the termination condition can read "p
less or equal address of element number 4 of array". put values , make concrete: imagine&a[0]
200
, consequence&a[4]
216
,p
incremented becomes204, 208, 212, 216
, ,220
. when becomes220
condition becomes false, , loop ends. - number 3's left side similar instead of increasing
p
addsi
p
. note magic of pointer arithmeticp + 1
p + i*(sizeof(*p))
. sequence same in case 2. btw, initialization shouldp = &a[0]
,i=0;
(note comma beforei
). right side(a+4)
, plain means address of first element of (this c equivalency between pointers , arrays,a
topic full of subtleties , pain).a + 4
equivalent&a[4]
. - number 4 there mess head. information above should enough translate initialization , condition; having both
i++
,p++
means advancing 2 elements each iteration.
the use of preprocessor here obscuring gets called, try expanding manually follow more easily. , prd should adding space after each number easier reading.
Comments
Post a Comment