rage said:
Can someone please help me out on this?
#include<stdio.h>
main()
{
int i;
int *j=10;
i=j+19;
printf("%d %d\n",j,i);
}
The output is a garbage value (86) on my pc and ideone. Should it not be 29?
The value 86 is not garbage, though the program that produced it is.
First off, "main()" should be "int main(void)". Most compilers will
probably accept "main()", but it's an obsolete form.
int *j = 10;
is a constraint violation. Your compiler should have either produced a
warning or rejected it outright, and you should have told us that. If
your compiler doesn't produce a diagnostic, then it's misbehaving; find
out how to invoke it so that it produces proper diagnostics.
If it's not rejected, the most likely behavior is that the compiler will
treat it as if you had written:
int *j = (int*)10;
which converts the int value 10 to int* and stores it in j. This is
almost certainly a nonsensical thing to do, but it's legal; the result
of the conversion is implementation-defined.
i = j + 19;
Since j is a pointer object, j + 19 performs pointer arithmetic. Given
a pointer value p and an integer value n, the expression p + n assumes
that p points to an element of an array and yields a pointer n elements
past the one that p points to. In other words, pointer arithmetic is
scaled by the size of the pointed-to type.
If sizeof (int) == 4 on your system, then j + 19 is likely to yield a
pointer to a location 76 bytes (19 int objects) past the location that j
points to.
printf("%d %d\n", j, i);
This has undefined behavior. The "%d" format requires an int argument,
but you're giving it an int*. But given a few plausible assumptions,
such as that int and int* happen to have the same size and that
conversions between pointers and integers just reinterpret the
representation without performing any other transformation, it's likely
that it will print
10 89
where 10 is the value of j (10 converted from int to int*, and the
interpreted as if it were an int), and 89 is the value of i
(10 + (4*19), but with several conversions from int to int* and
back again).
The only thing you really *need* to know about this program is that
it's invalid. You have several instances of undefined behavior, and
one constraint violation, requiring a compile-time diagnostic that
*you should not ignore*. The above is a plausible explanation of
the behavior you're seeing -- but it could be completely different
on another system, or on the same system with different options,
or it could be rejected altogether.