Question about Pointer arithmetic | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

Question about Pointer arithmetic

My question is in this code: https://code.sololearn.com/cXZnR0ev9DX2

19th Jun 2022, 10:35 AM
Edward Finkelstein
Edward Finkelstein - avatar
2 Antworten
+ 2
the C standard states the following regarding pointer subtraction (section 6.5.6p9): " When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the header. If the result is not representable in an object of that type, the behavior is undefined. In other words, if the expressions P and Q point to, respectively, the i -th and j -th elements of an array object, the expression (P)-(Q) has the value i−j provided the value fits in an object of type ptrdiff_t . Moreover, if the expression P points either to an element of an array object or one past the last element of an array object, and the expression Q points to the last element of the same array object, the expression ((Q)+1)-(P) has the same value as ((Q)-(P))+1 and as -((P)-((Q)+1)) , and has the value zero if the expression P points one past the last element of the array object, even though the expression (Q)+1 does not point to an element of the array object. " p1 is a pointer to the beginning of the array, and arg[1] is the same as *(arg+1). so you could say that the "&" cancels the "*" as you dereference the pointer and then look at the address of the element that it points to. so : *p1 = &(arg[0]) = &(*(arg+0)) = arg and &arg[1] = &(*(arg+1))=arg+1 therefore: &arg[1]-p1 = arg + 1 - arg = 1.
19th Jun 2022, 12:17 PM
MO ELomari
0
Ani Jona 🕊 it certainly would explain it, but i think Mohamed ELomari has the actual answer, that “the result is the difference of the subscripts of the two array elements”. So it’s a part of the C standard. I guess you could think of it as the number of blocks of memory, where a block is the amount of memory for 1 object, but the bottom line i think is that it’s the standard.
19th Jun 2022, 1:57 PM
Edward Finkelstein
Edward Finkelstein - avatar