【问题标题】:"assignment from incompatible pointer type [enabled by default]"?“来自不兼容指针类型的赋值[默认启用]”?
【发布时间】:2015-01-17 13:14:29
【问题描述】:

我是 C 的新手,并尝试使用以下两个结构编写一个在列表开头插入节点的函数:

typedef struct singly_linked_list_node {
    char *data; 
    struct singly_linked_list_node *next;
} node;

typedef struct singly_linked_list_head {
    struct node *first;
    struct node *last;
    int size;
} sin_list;

我的功能是

void insert_at_start(sin_list* list, char *str)
{
    int length;
    node *newnode;
    newnode = malloc(sizeof(node));
    length = strlen(str) + 1;
    newnode->data = malloc(sizeof(length));
    strcpy(newnode->data, str);
    newnode->next = list->first;
    list->first = newnode;
    if (list->last == NULL) list->last = newnode;
}

当我编译时,我收到最后 3 行的警告“来自不兼容指针类型的赋值 [默认启用]”,所以很明显我缺少一些东西。

【问题讨论】:

  • nodelist的类型不匹配
  • 顺便说一句 newnode->data = malloc(sizeof(length)); --> newnode->data = malloc(length);
  • 为什么需要struct singly_linked_list_head
  • struct node *first; struct node *last; --> node *first; node *last;
  • @user7 我需要一个指向列表第一个节点的指针,一个指向最后一个节点的指针和一个 int 大小,以便打印列表中“项目”/节点的数量

标签: c pointers struct gcc-warning


【解决方案1】:

使用struct singly_linked_list_head 的定义,您可以对struct 类型使用两个隐式前向声明。这些是

struct node *first;
struct node *last;

您还有node 的类型定义。 struct node 类型永远不会被解析,但只要您只使用指向它的指针,编译器就可以了。在C 语言中,结构名称和类型定义有两个不同的名称空间。

通过使用你的 typedef 来修复你的代码:

typedef struct singly_linked_list_head {
    node *first;
    node *last;
    int size;
} sin_list;

编辑当您分配内存时,您应该使用str 的长度而不是变量length 的大小来为data 分配内存:

length = strlen(str) + 1;
newnode->data = malloc(sizeof(length));

改为:

length = strlen(str) + 1;
newnode->data = malloc(length);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 2019-08-09
    • 2014-12-14
    • 2019-06-05
    • 2015-03-09
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多