简体   繁体   中英

Confusion when assigning address using C

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);
  }

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);

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM