Unexpected result when added to index

Someone told me that this piece of code prints 29. Why is this?

int *a = 17; printf("%d", a+3); 
+6
c undefined-behavior
source share
5 answers

Because when you add a pointer, it adds the size of the object. In this case, the size of the object is 4 (sizeof (int) == 4) - so 17 + 3 * 4 == 29.

+36
source share

Everyone knows that the answer is 23, at least at 6809.

 a+3 == a + (3 * sizeof(int)) == a + 6 == 17 + 6 == 23 
+13
source share
 a+3 == a + (3 * sizeof(int)) == a + 12 == 17 + 12 == 29 
+11
source share

Integral values ​​cannot be initialized in C pointers, with the exception of a single constant expression that evaluates to integer zero. 17 does not satisfy this requirement.

The code is invalid. He doesn't β€œprint” anything. The question makes no sense. Any attempt to analyze this issue in terms of pointer arithmetic is a ridiculous and useless waste of time.


ISO / IEC 9899: 1999 (programming languages ​​- C)

6.5.16.1 Simple assignment

Limitations

Assume one of the following: 93)

- the left operand has a qualified or unskilled arithmetic type, and the right one has an arithmetic type;

- the left operand has a qualified or unqualified version of the structure or type of association is compatible with the type of law;

- both operands are pointers to qualified or unqualified versions of compatible types, and the type that the left points to has all the qualifiers of the type that the right points to;

- one operand is a pointer to an object or an incomplete type, and the other is a pointer to a qualified or unqualified version of void, and the type that the left points to has all the type qualifiers that it points to from the right;

- the left operand is a pointer, and on the right is the constant of the null pointer; or

- the left operand is of type _Bool, and the right is a pointer.

93) The asymmetric form of these restrictions with respect to type classifiers is due to the conversion (specified in 6.3.2.1), which changes the lvalues ​​to the `` value of the expression, which removes any type qualifiers from the type category of the expression.

+2
source share

can print anything .. you set the pointer to the location "17" in memory ...

-2
source share

All Articles