SE250:lab-2:rbha033/task2

From Marks Wiki
Jump to navigation Jump to search

This was the code for Task 2:

#include <stdio.h>
int main(){
    int x,y;
    printf("&x=%p, &y=%p, diff=%ld\n", &x, &y, (long)(&x-&y));
    printf("(long)&x - (long)&y = %ld\n(long)(&x-&y) = %ld\n", (long)&x-(long)&y, (long)(&x-&y));
    return 0;
}

The Output was:

gcc -o task2 task2.c && ./task2.exe
&x=0x22ccc4, &y=0x22ccc0, diff=1
(long)&x - (long)&y = 4
(long)(&x-&y) = 1

Compilation finished at Tue Mar 11 11:25:20

Question: What's the difference between (long) &x - (long) &y and (long) (&x - &y)?

Answer: (long)(&x) - (long)(&y) = 4, while (long) (&x - &y) = 1. I don't know why this is but I need to find out.

After speaking to john I was told that this is because C creates an illusion of memory chunks, and the first time it's showing us the actual address difference is 4 bytes, since each int type is 4 bytes long, while the second time its telling us that there's a difference of 1 int type between the 2 addresses. (Rbha033 12:22, 11 March 2008 (NZDT))