unexpected result when adding to pointer
Someone told me this bit of code pri开发者_StackOverflownts 29. Why is that?
int *a = 17;
printf("%d", a+3);
Because when you add to a pointer it adds the object size. In this case the object size is 4 (sizeof(int) == 4) -- so 17 + 3 * 4 == 29.
Everyone knows the answer is 23, at least on the 6809.
a+3 == a + (3 * sizeof(int)) == a + 6 == 17 + 6 == 23
a+3 == a + (3 * sizeof(int)) == a + 12 == 17 + 12 == 29
In C language pointers cannot be initialized with integral values, with the only exception of an Integral Constant Expression that evaluates to integral zero. 17
does not satisfy that requirement.
You code is invalid. It doesn't "print" anything. The question makes no sense whatsoever. Any attempts to analyze this question from the point of view of the pointer arithmetic are ridiculous and just useless waste of time.
ISO/IEC 9899:1999 (Progamming Languages - C)
6.5.16.1 Simple assignment
Constraints
One of the following shall hold:93)
— the left operand has qualified or unqualified arithmetic type and the right has arithmetic type;
— the left operand has a qualified or unqualified version of a structure or union type compatible with the type of the right;
— both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
— one operand is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
— the left operand is a pointer and the right is a null pointer constant; or
— the left operand has type _Bool and the right is a pointer.
93) The asymmetric appearance of these constraints with respect to type qualifiers is due to the conversion (specified in 6.3.2.1) that changes lvalues to ‘‘the value of the expression’’ which removes any type qualifiers from the type category of the expression.
can print anything .. you are setting a pointer to the location '17' in memory ...
精彩评论