【问题标题】:Pointer that points to return of function. Initialization from incompatible pointer type指向函数返回的指针。从不兼容的指针类型初始化
【发布时间】:2011-05-11 09:45:23
【问题描述】:

我在使用指针时遇到了一些问题。我有一个函数应该返回链表中的节点,该函数应该返回指向变量的指针。我很困惑,看不出我做错了什么!

data.h - 头文件

int add(int num);
struct message *findMessage(int num);

typedef struct list_el message;

data.c - 链表。

    #include <stdio.h>
#include <stdlib.h>

struct list_el {
    int num;

    struct list_el *next;

};

typedef struct list_el message;
struct list_el *head, *tail;



int addNode(struct list_el *curr)
{
    if(head == NULL) {
        head = curr;

    } else {
        tail->next = curr;
    }

    curr->next = NULL;

    return 0;
}

int add(int num)
{
    message *curr;

    head = NULL;

    curr = (message*) malloc(sizeof(message));
    curr->num = num;
    addNode(curr);

    return 0;
}

message *findMessage(int num)
{
    message *curr;

    for(curr = head; curr != NULL; curr = curr->next) {
        if(curr->num == num) {
            return curr;
        }
    }
    return NULL;
}

Main.c - 主要

#include <stdio.h>

#include "data.h"

int main(void)
{
 int num = 2;

 add(num);

 message *curr = findMessage(num);

 return 0;
}

【问题讨论】:

  • 您实际上并没有在 add/addNode 中分配新节点 - 您需要调用 malloc 来分配存储空间。
  • 嗨。抱歉,我只是将其编码为示例。现在已经更正了,但是指针问题还没有解决。
  • @user265767:不——上面发布的代码仍然有问题——你没有分配任何节点。
  • 与问题无关,但tail-&gt;prev = tail; 毫无意义——您将尾节点链接到自身。
  • 仍有许多简单/明显的错误 - 尝试在调试器中单步执行代码

标签: c pointers


【解决方案1】:

为什么不在标题中包含struct list_el 的定义?否则main 无法使用。

【讨论】:

  • 那不是和我一样的typedef吗?
  • @user:不,标题必须包含实际的结构声明。否则任何外部代码都无法使用它:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多