typedef struct dict_pair {
void *key;
void *value;
struct dict_pair *head;
struct dict_pair *tail;
} dict;
dict* NewDictionary(void) {
dict *dictionary = malloc(sizeof(dict_pair));
dictionary->head = null;
dictionary->tail = null;
}
int main(void) {
dict *dictionary = NewDictionary();
}
Run Code Online (Sandbox Code Playgroud)
我最初计划将结构设置为null,但编译器不允许它.如何检查结构是否已分配?
另外,我可以在结构中以递归方式声明相同的结构吗?
C没有null,它有NULL.试试这个:
dict* NewDictionary(void) {
return calloc(sizeof(dict));
}
Run Code Online (Sandbox Code Playgroud)
这解决了一些问题:
value并且没有key初始化,所以他们可以随意丢垃圾.使用calloc()将把所有内容初始化为0,在指针上下文中NULL.它甚至不会花费更多的处理时间.return陈述的情况下运作结束,那么只有幸运的是,任何东西都会被退回.dict_pair代替struct dict_pair.在C++中,struct名称在常规类型命名空间中,即t x = { 0 };有效的C++,但在C中你需要说struct t x = { 0 };.malloc()(现在calloc()但适用相同的规则)的返回值.如果内存不足,则calloc()返回NULL.我讨厌NULL在事故中取消引用指针.我们不必在这里检查返回值,因为我已经废除了所有中间步骤 - calloc()对我们来说已经足够了.请注意,calloc()可移动性稍差.尽管标准确实要求void *p = 0将指针设置为空指针,但它并不要求空指针"将所有位设置为零",这在calloc()技术上是这样做的.如果你不想calloc()因为这个原因使用,这里有一个版本做同样的事情malloc():
dict* NewDictionary(void) {
dict *dictionary = malloc(sizeof(dict));
if(dictionary) {
dictionary->head = NULL;
dictionary->tail = NULL;
dictionary->value = NULL;
dictionary->key = NULL;
}
return dictionary;
}
Run Code Online (Sandbox Code Playgroud)
要么:
dict* NewDictionary(void) {
dict *dictionary = malloc(sizeof(dict));
if(dictionary == NULL) return NULL;
dictionary->head = NULL;
dictionary->tail = NULL;
dictionary->value = NULL;
dictionary->key = NULL;
return dictionary;
}
Run Code Online (Sandbox Code Playgroud)
看看calloc()版本有多好?
至于你的第二个问题:
另外,我可以在结构中以递归方式声明相同的结构吗?
不,你不能这样做:
struct t {
struct t x;
}
Run Code Online (Sandbox Code Playgroud)
但你可以这样做(这是你正在做的,你想要的):
struct t {
struct t *x;
}
Run Code Online (Sandbox Code Playgroud)
你可以有一个指针到struct内部struct本身,而是你不能有实际的struct内部struct本身.你正在做的事情是完全合法的,因为你正在使用指针.