-4

I am trying to assign the address of one of a structure, which is named as node, to another one named tmp, which has the same type--Node. However, the address of tmp is always less 8 then the address of node. Why is that? thanks!

  #include <stdio.h>
  #include <stdlib.h>

  typedef struct _node
  {
    int data;
    struct _node *next;
  }Node;

  int main()
  {
    Node *node = (Node*)malloc(sizeof(Node));
    Node *tmp;
    tmp = node;

    printf("%d\n",&node);
    printf("%d\n",&tmp);
  }
KennyYang
  • 235
  • 2
  • 13
  • 2
    Your system stores `node` and `tmp` next to each other in memory, which is not surprising since they are declared next to each other. What did you expect the difference of addresses to be? – M.M Sep 13 '16 at 05:38
  • 4
    Also, Do *NOT* cast the return of `malloc`, it is unnecessary. See: [**Do I cast the result of malloc?**](http://stackoverflow.com/q/605845/995714) for thorough explanation. `Node *node = malloc(sizeof *node);` is all that is required. – David C. Rankin Sep 13 '16 at 05:41

3 Answers3

1

I am guessing that you expected the output to be the same for both lines.

For that to happen, you have to print the values of the pointers, not the addresses of the pointers.

After

tmp = node;

the value of tmp is the same as the value of node but the addresses of the two variables are always going to be different.

I suspect you meant to use:

printf("%p\n", node);  // Use %p for pointers, not %d
printf("%p\n", tmp);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Likely pointers are 8 bytes on your platform. So since you allocated one right after the other, they are 8 bytes apart.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

You are confused about the difference between the value of a variable (of pointer type) and its address. You can change the value of a variable, as you do in your code by means of the assignment operator:

tmp = node;

but a variable's address is the most essential of its defining characteristics. You cannot change that.

You are printing the addresses of your pointers (sort of -- the field descriptors in your format string are wrong). To print their values, you want this:

    printf("%p\n", (void *) node);
    printf("%p\n", (void *) tmp);

The key distinction is of course that the above does not employ the address-of operator (&). Additionally, the %p field descriptor is what you need to print a pointer value, but it is specifically for void * values. And that's the reason for the casts.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157