【问题标题】:A value type "node" cannot be used to intialize an entity of type "struct node"值类型“节点”不能用于初始化“结构节点”类型的实体
【发布时间】:2021-06-30 14:39:50
【问题描述】:

我有两个函数,其中一个调用另一个函数,标题是我得到的错误。我只是想知道我是否缺少一个简单的修复程序。如果需要更多信息,请告诉我。谢谢!

node createNode() {
newNode temp;//declare node
temp = (newNode)malloc(sizeof(struct node));//allocate memory
temp->next = NULL;//next point to null
return *temp;// return the new node
} 
void enqueue(queue* q, customer* data) {
// Create a new LL node
struct node* temp = createNode(data);//error line

【问题讨论】:

  • createNode 应该返回一个node *
  • typedef struct node node; 存在于任何地方?
  • 发布代码或错误时请准确无误。在您的错误消息中似乎缺少*。您尝试初始化类型 struct node* 而不是 struct node

标签: c struct queue nodes


【解决方案1】:

你想要一个返回值struct node*,所以返回类型应该是struct node*

还将指向struct node 的指针命名为newNode 看起来很混乱(至少对我而言),所以你不应该这样做。

还有一点,malloc()family 的转换结果是considered as a bad practice

最后,你应该检查malloc()是否成功。

struct node* createNode() { /* use proper return type */
    /* use non-confusing type */
    struct node* temp;//declare node
    temp = malloc(sizeof(struct node));//allocate memory
    if (temp == NULL) return temp; /* check if allocation succeeded */
    temp->next = NULL;//next point to null
    /* remove dereferencing */
    return temp;// return the new node
} 
void enqueue(queue* q, customer* data) {
    // Create a new LL node
    struct node* temp = createNode(data);//error line

同样,参数 data 被传递但被忽略,这看起来很奇怪,但我不会解决这个问题,因为我不知道如何解决。

【讨论】:

  • 也许使用calloc 而不是malloc 可以确保结构完全初始化为零。这会稍微慢一些,但要确保所有内容都具有已知值,如果稍后忘记某些内容(如指针初始化),则可能会产生明显的段违规,即未定义的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 2018-07-23
  • 2022-01-25
相关资源
最近更新 更多