简体   繁体   中英

Pointers to structures as structure members

I am working my way through Sam's Teach Yourself C in 21 Days and I've run into a code snippet that I can't wrap my head around. This is from Day 11, Exercise 6. The task is "write the definition for a structure type named data that can hold a string of up to 20 characters." My solution was

struct data{
    char a[21];
};

Dumb use of a structure, but ok. My dummy code compiles and produces the expected result of 21

#include <stdio.h>

struct data{
    char a[21];
} data_inst;

int main(void)
{
    printf("%lu\n", sizeof(data_inst.a));

    return 0;
}

However, the answer according to the book is

struct data{
    char a[21];
    struct data *ptr;
};

My interpretation of the correct answer is that ptr is a pointer to type data . But ptr is also a member of data . What is the point of this additional line? What is the benefit of a structure that contains a pointer to itself? Or am I just missing something completely here?

A pointer in the structure is used to store the address of the next structure it's generally used in the linked list where we want to store the address of the next node so it becomes connected. You can search about the linked list you will get detailed information that how the linked list works and according to your code, there is no need for struct data *ptr because you only need to make a structure with 20 characters. and for your question what is the use of struct data *ptr you can refer to the linked list.

The pointer does not point to this structure, but to a structure of this type. Sure it could point to itself, but it can also point to another instance of the same struct type.

So you can keep or point to a first instance of data , and if necessary, it can in turn point to another one and so on. This would allow you to keep up to 20 characters (or sacrificing null string termination, up to 21 with unambiguously) in one such instance, but use more than one instance to either: 1/ store strings exceeding 21 characters over more than one instance 2/ store a list or stack of strings of up to 21 characters

If you define string as proper c style null terminated string, then of course it can only be up to 20. Otherwise you can use null for strings of length less than 21, and just avoid using null for strings of length 21 - you know that there can be nothing after 21st character anyway.

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