gpt4 book ai didi

C 编程编译问题

转载 作者:行者123 更新时间:2023-11-30 18:41:31 25 4
gpt4 key购买 nike

嘿伙计们,我正在准备面试,大部分编程将用 C 完成。我决定用 C 实现一个链接列表类,以便了解对象是如何在不支持的较低级语言中真正实现的面向对象的范例。我遇到了一些编译问题,所以任何熟悉 C 的人请帮忙(我从未用 C 编程)。我在下面发布了我的代码以及紧随其后的编译错误。

//Creating a LinkedList in C
//with 3 basic operations
#include <stdio.h>
typedef struct node {
int data;
node* next;
} List;

void insertEnd(List *node, int elem);
void PrintList(List *node);
/*void insertEnd(List *node, int elem);
void remove(List *node, int elem);*/

int main () {
List *head = (List *)malloc(sizeof(List));
head->data = 0;
head->next = NULL;
insertEnd(head, 3);
insertEnd(head, 4);
PrintList(head);
}
void insertEnd(List *node, int elem) {
while (node->next != NULL) {
node = node->next;
}
List *new_node = (List *)malloc(sizeof(List));
new_node->data = elem;
new_node->next = NULL;
node->next = new_node;
}

void PrintList(List *node) {
while (node) {
printf ("%i ->", node->data);
node = node->next;
}
}

错误如下:

bash-4.1$ gcc -o LinkedList LinkedList.c
LinkedList.c:6: error: expected specifier-qualifier-list before ‘node’
LinkedList.c: In function ‘main’:
LinkedList.c:15: warning: incompatible implicit declaration of built-in function ‘malloc’
LinkedList.c:17: error: ‘List’ has no member named ‘next’
LinkedList.c: In function ‘insertEnd’:
LinkedList.c:24: error: ‘List’ has no member named ‘next’
LinkedList.c:25: error: ‘List’ has no member named ‘next’
LinkedList.c:27: warning: incompatible implicit declaration of built-in function ‘malloc’
LinkedList.c:29: error: ‘List’ has no member named ‘next’
LinkedList.c:30: error: ‘List’ has no member named ‘next’
LinkedList.c: In function ‘PrintList’:
LinkedList.c:36: error: ‘List’ has no member named ‘next’

最佳答案

成员 next 应使用 struct node *next 声明,并且必须包含 stdlib.h,其中包含 的声明>malloc:

并且您必须使用 -Wall 标志进行编译,直到您的程序没有错误为止。

#include <stdlib.h>

// ...

typedef struct node {
int data;
struct node *next;
} List;

// ...

关于C 编程编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20967316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com