Search code examples
cmemory-address

Memory and adress of struct type in C Language?


1.background
  • Althought I found the build-in types in C work similar to struct type, but i find something different.

  • No knowledge of assembly language

2.Test code
// @compiler: gcc
// @machine: x64 Windows
#include <stdio.h>

struct IntNode {
    int integer;
    struct IntNode * next;
};

int main() {
    struct IntNode ints_list = {0, 0};
    printf("size of IntNode: %d\n", sizeof(struct IntNode));
    printf("Address of ints_list         : %p\n",  ints_list);         // 000000000061FE00
    printf("Address of &ints_list        : %p\n", &ints_list);         // 000000000061FE10
    printf("Address of &ints_list.integer: %p\n", &ints_list.integer); // 000000000061FE10
    printf("Address of &ints_list.next   : %p\n", &ints_list.next);    // 000000000061FE18
}
3.Picture

3.question
  • Why ints_list stand that memory

  • whether ints_list is in variables table when app is compiled?


Solution

  • ints_list is not the address of a structure, &ints_list is - your first printf invokes undefined behavior.

    structs can be passed by value, and passing one to printf (that doesn't have the slightest idea how your structure should be printed) disguised as a pointer produces garbage output.