Some analysis of structure address and structure pointer

Keywords: C++ C

  when I was learning the implementation of linked list in C language, I encountered some problems. Generally, the header of linked list is created through the structure, and the header contains the information such as the first node to be pointed to and the length of the whole linked list. I was a little confused about the address information stored in the header.
For example, a one-way linked list is created as follows:

typedef struct _tag_LinkListNode LinkListNode;       //Node alias

struct _tag_LinkListNode
{
    LinkListNode* next;
};       // Definition of node pointer field      

typedef struct _tag_LinkList
{
    LinkListNode header;
    int length;
} TLinkList;        //Definition of head node

struct Value
{
    LinkListNode header;
    int v;
};           //Data field definition

At this time, there are the following problems:
1. What does the header in tlinklist store?
2. What is the length of tlinklist?
3. How is the link list of tlinklist associated with the first node?

void main(void)
{
    struct  Value v1;
    v1.v = 1;

    TLinkList* list = (TLinkList*)malloc(sizeof(TLinkList));    //Create linked list
    LinkListNode* current = (LinkListNode*)list;             //Cast list to type

    printf("list size is %d\n",sizeof(list));
    printf("&list address is %p\n", &list);                      
    printf("list address is %p\n", list);
    printf("&(list->header) address is %p\n", &(list->header));

    printf("TLinkList size is %d\n", sizeof(TLinkList));
    printf("list->header value is %p\n",list->header);
    printf("&v1 address is %p\n", &v1);
    printf("&(v1->header) address is %p\n", &(v1.header));
    printf("&(list->length) address is %p\n", &(list->length));
    printf("list length value is %d\n", list->length);
    free(list);
}

The output result is;

list size is 4
&list address is 0113FBE8
list address is 014CF558
&(list->header) address is 014CF558
TLinkList size is 8
list->header value is 0113FBF4
&v1 address is 0113FBF4
&(v1->header) address is 0113FBF4
&(list->length) address is 014CF55C
list length value is 0

According to the output results, it is known that the address stored in the header is the address to the node, and the length of TLinkList is 8. The address can be expressed as follows:

Posted by jonathanellis on Sat, 30 Nov 2019 20:50:47 -0800