On 3/19/07, Gustavo Rios <[EMAIL PROTECTED]> wrote:
On 3/19/07, Nick ! <[EMAIL PROTECTED]> wrote: > On 3/19/07, Gustavo Rios <[EMAIL PROTECTED]> wrote: > > I am writing a very simple program but the output change for the c > > variable value change every time i run it. What would it be my mistake > > on the source? Did i forget some thing? > > > > #include <stdio.h> > > > > int > > main(int argc, char **argv) > > { > > unsigned long long x, c; > > unsigned *p; > > ^ this is bad. always say your types in full. > > > > > x = 1, x+= (unsigned long long)1 << 33 ; > > This sets *(&x) to 1, and then sets *(&x) (yes, the same one) to 1+(1<<33) > > > p = (void *)&x; > > c = p[0] * p[1]; > > That is, p[1] == *(&x+1) is never getting set to anything. Thus the > reason the output is always changing is because p[1] is always > pointing at a different, random location in memory that has some > previous value. > > Further, p[1] is not your memory, and it's only by chance that you're > not segfaulting. > > > fprintf(stdout, "x:%llu\n", x); > > fprintf(stdout, "0,1:%u,%u\n", p[0], p[1]); > > fprintf(stdout, "c:%llu\n", c); > > > > return 0; > > } > > So, why when i printf p[1], it correctly prints 2?
Uhm. Hmm. Well, x is a long long which is 8 bytes right? A void (when doing pointer arithmetic) is taken to only be 1 byte (right?). So p[0] is the first byte of those 8, and p[1] is the second, and due to coincidence and twos-complement encoding it happens to show you the expected numbers. Maybe? But that doesn't explain why the output is always changing. Wait, how is * defined on two voids????? That shouldn't even compile (unless it's autocasting to int?). -Nick