Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

recursion - Initialize recursive struct type in C properly

I am new to C programming and I have the following struct:

typedef struct _date {
    char d[10], t[5], s[3];
    struct _date *next;
} *date;

How can I properly create an instance of this?

My solution:

date neuerTermin(char *d, char *t, char *s, date cal) {
    struct _date d = {*d, *t, *s, NULL};
    date d_ptr = malloc(sizeof *d);
    cal->next = d_ptr;

    return d;
}

But I get an error: warning: initialization makes integer from pointer without a cast

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it as follows:

#include <stdio.h>

typedef struct _date {
    char d[11], t[6], s[4]; // +1 to size for null-terminator ('')
    struct _date *next;
} *date;


int main() {
    struct _date a = { "15.07.2017", "16:00", "Foo", NULL };
    date a_ptr = &a;

    printf("Description: %s
Date: %s
Time: %s
", a_ptr->s, a_ptr->d, a_ptr->t);
    return 0;
}

The brace-enclosed, comma-separated list in the example above is the struct initializer.


To respond to the edits of your question, if you wish to dynamically allocate struct _date instances and initialize them in a function, then use malloc as follows:

date neuerTermin(const char* d, const char* t, const char* s) {
    date cal = (date)malloc(sizeof(struct _date));

    strncpy(cal->d, d, 10);
    strncpy(cal->t, t, 5);
    strncpy(cal->s, s, 3);
    cal->next = NULL;

    return cal;
}

In this case you have to fill the memory block pointed by cal member-by-member. Sample usage:

date root = neuerTermin("15.07.2017", "16:00", "Foo");
root->next = neuerTermin("27.07.2017", "10:00", "Bar");
root->next->next = neuerTermin("01.08.2017", "12:30", "Baz");

Important: if you used malloc to allocate memory, you have to deallocate it too with using free when you don't need it anymore.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...