Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected result when adding to pointer

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

int *a = 17; 
printf("%d", a+3);
like image 612
AK_ Avatar asked Dec 15 '09 20:12

AK_


4 Answers

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.

like image 127
Aaron Avatar answered Sep 17 '22 13:09

Aaron


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

a+3 == a + (3 * sizeof(int)) == a + 6 == 17 + 6 == 23
like image 24
Richard Pennington Avatar answered Sep 19 '22 13:09

Richard Pennington


a+3 == a + (3 * sizeof(int)) == a + 12 == 17 + 12 == 29
like image 34
JSBձոգչ Avatar answered Sep 19 '22 13:09

JSBձոգչ


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.

like image 36
AnT Avatar answered Sep 21 '22 13:09

AnT