【问题标题】:struct becomes NULL结构变为 NULL
【发布时间】:2015-03-20 02:17:45
【问题描述】:

我想实现一个类似于 OOP 的链表实现。

#include <ctype.h>
#include <string.h>
#include <stdlib.h>

typedef struct node {
    char data[100];
    struct node *next;
    struct node *prev;
}Node;

typedef struct treeNode {
    char treeData[100];
    struct treeNode *left;
    struct treeNode *right;
}TreeNode;

typedef struct sql_struct{
    Node *head, *tail;
}StackQueueList;

typedef struct tree {
    TreeNode *root;
}Tree;

void initStackQueueList(StackQueueList* a) {
    a->head = a->tail = NULL;
}///initStackQueueList

Tree* initTree (Tree* a) {
    a->root = NULL;
}///newTree

但问题是,每当我使用initStackQueueList() 时,它总是让人觉得指针是NULL,这有点道理,因为我希望它里面的 VALUES 为空,而不是指针本身为空。所以很可能,我在这里实现了一些错误,我无法理解它,所以我正在寻求帮助! :)

示例实现:

static const StackQueueList *dqFriend1, *dqFriend2, *dqMyself, *dqVirus;

void initQueues () {
    initStackQueueList(dqFriend1);
    initStackQueueList(dqFriend2);
    initStackQueueList(dqMyself);
    initStackQueueList(dqVirus);
}

=更正版本=

StackQueueList *dqFriend1, *dqFriend2, *dqMyself, *dqVirus;
*dqFriend1 = *dqFriend2 = *dqMyself = *dqVirus = (StackQueueList*) malloc(sizeof (StackQueueList));

void initQueues () {
    initStackQueueList(dqFriend1);
    initStackQueueList(dqFriend2);
    initStackQueueList(dqMyself);
    initStackQueueList(dqVirus);
}

但现在我遇到了这些错误:

error: conflicting types for 'dqFriend1'|
error: incompatible types when assigning to type 'StackQueueList' from type 'struct StackQueueList *'|

【问题讨论】:

  • 这将是使用调试器的好时机,并“监视”导致问题的变量。
  • 一般来说,当期望某个函数填写指向某个数据的指针时,通常会传递指针变量的地址,而不是指针变量的内容。建议:initStackQueueList( &dqFriend1 );
  • 为了安全起见,指针的声明应该将它们初始化为 NULL。如果每个指针都声明在单独的行上,那是最清楚的。
  • 在 C 中,结构定义不应包装在 typedef 中。 typedef 使代码变得模糊/混乱,并使编译器名称空间变得混乱。
  • @user3629249 感谢您的提示。我稍后会尝试,但我目前正在尝试解决这个问题,正如这里的人们所指出的那样,我实际上是在传递一个 NULL 结构,因为我忘记为他们分配内存。

标签: c struct tree linked-list


【解决方案1】:

您应该首先为指针dqFriend1dqFriend2dqMyselfdqVirus 分配空间。否则他们的成员将没有位置。

eg. dqFriend1 = (StackQueueList*)malloc(sizeof(StackQueueList));

【讨论】:

  • 我实际使用了watch实用程序,值为0x0,这意味着StackQueryList为空。接得好!但是当我这样做时,我遇到了一个错误类型冲突的问题。有什么想法可以解决这个问题?
  • 谢谢@PatJ!在变量之前删除指针就可以了!哈哈哈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
相关资源
最近更新 更多