【发布时间】:2016-09-20 04:22:12
【问题描述】:
我有一个类型node,它的指针正在另一个结构中使用,如下所示。
typedef struct element {
void* data;
struct element *next;
} node;
typedef struct queue {
node *tail;
node *head;
int num_items;
} queue_t;
我使用以下代码创建了一个空队列,但我不确定是否应该将 head 和 tail 设置为 NULL,因为 temp 还没有指向任何地方。
queue_t *temp;
temp = malloc(sizeof(queue_t));
if (temp == NULL){
return NULL;
}
temp->head = NULL;
temp->tail = NULL;
temp->num_items = 0;
根据我的理解,malloc 只会将临时指向某个地址空间,其大小等于struct queue_t 的大小。地址空间尚不包含有效的队列元素。那么temp->head = NULL; 和temp->tail = NULL; 是怎样的有效语句呢?
有人可以解释一下为什么会这样吗?
【问题讨论】:
-
如果你在标题中说“C”,也不要用 C++ 标记。选择一种语言;坚持下去。
-
代码中没有
struct Node;你有一个struct element,也称为node,你有一个struct queue,也称为queue_t。 -
您分配了一个“结构队列”(又名 queue_t),然后在分配的结构中设置成员变量的值。为什么它不起作用? (也许您读到了有关未定义分配空间中的字节的信息?这是真的,但只有当您读取未定义的值而不是覆盖它们时才会出现问题)