在 C 中正确初始化递归结构类型 [英] Initialize recursive struct type in C properly
问题描述
我是 C 编程的新手,我有以下结构:
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;
如何正确创建此实例?
我的解决方案:
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;
}
但我收到一个错误:warning: 初始化从指针生成整数而无需强制转换
推荐答案
您可以这样做:
#include <stdio.h>
typedef struct _date {
char d[11], t[6], s[4]; // +1 to size for null-terminator ('\0')
struct _date *next;
} *date;
int main() {
struct _date a = { "15.07.2017", "16:00", "Foo", NULL };
date a_ptr = &a;
printf("Description: %s\nDate: %s\nTime: %s\n", a_ptr->s, a_ptr->d, a_ptr->t);
return 0;
}
上例中用大括号括起来的逗号分隔列表是 struct 初始化程序.
The brace-enclosed, comma-separated list in the example above is the struct initializer.
为了回应您的问题的编辑,如果您希望动态分配 struct _date
实例并在函数中初始化它们,请使用 malloc
如下:
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;
}
在这种情况下,您必须逐个填充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");
重要提示:如果您使用 malloc
分配内存,您也必须使用 free
当您不再需要它时.
Important: if you used malloc
to allocate memory, you have to deallocate it too with using free
when you don't need it anymore.
这篇关于在 C 中正确初始化递归结构类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!