C - 调用'number::number(void)'没有匹配功能



你好,我正在尝试编写一个链表,但它不起作用。Malloc在第一个和最后一个指针返回了一个不匹配的函数来调用

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

typedef struct number{
int x;
struct number *next;
}Number;

Number *first = NULL, *temp = NULL, *last = NULL;

void insert(int x){

if(first==NULL){

first= (Number)malloc(sizeof(Number));
first->x=x;
first->next = NULL;
temp=first;
}
else{
last = (Number)malloc(sizeof(Number));
last->x = x;
last->next = NULL;
temp->next =last;
temp=last;
}


}

void printList(){
Number *hold = first;

while(hold!=NULL){
printf("n%dn",hold->x);
hold = hold->next;
}
}


int main(){

int size;
printf("Enter size: ");
scanf("%d",&size);
Number *hold = first;

printf("Enter value:n");



for(int i=0;i<size;i++){
int x;
scanf("%d",&x);
insert(x);
}

printfList();
}

这里可能出了什么问题?

  1. 错误消息听起来像是用c++而不是c编译器编译的
  2. Numberstruct Number的typedef,但您将其用作指针。在c中,我们不抛出void指针,所以忽略它:
void insert(int x) {
if(first==NULL){
first = malloc(sizeof(Number));
first->x=x;
first->next = NULL;
temp = first;
} else {
last = malloc(sizeof(Number));
last->x = x;
last->next = NULL;
temp->next = last;
temp = last;
}
}
  1. printfList()应为printList()

这里有一个执行示例:

Enter size: 3
Enter value:
1
2
3
1
2
3
  1. 我建议您消除全局变量,并将它们传递给需要它们的函数。特别地,tempinsert()的实现细节。

  2. 此外,不一致的格式,意味着我立即不信任你的代码。格式化对可读性很重要,为什么要让它对你自己来说很难呢?

您的"插入";逻辑(实际上是"追加"(是不稳定的。分配了区域,但返回的地址很快就会丢失。

void insert( int x ) {
temp = malloc( sizeof *temp ); // Make a node
/* omitting test for NULL */
temp->x = x; // populate its members
temp->next = NULL;
if( first == NULL )
first = temp; // all done!
else
last = last->next =  temp; // all done here, too!
}

问题是您将first声明为该行中的指针

Number *first = NULL, *temp = NULL, *last = NULL;

但是当您尝试使用malloc时,malloc返回类型为void的指针,因此您应该将其强制转换为(Number*)而不是(Number),您应该将void pointer强制转换为Number pointer

所以不是

first = (Number)malloc(sizeof(Number));

你应该做

first = (Number*)malloc(sizeof(Number));

参考malloc((手册,因为malloc的原型是

void*malloc(size_t-size(;

和一个小语法错误,它不是

printfList();

它是:

printList();

通过这些小的编辑,这是最后的代码:

#include <stdio.h>
#include <stdlib.h>
typedef struct number{
int x;
struct number *next;
}Number;
Number *first = NULL, *temp = NULL, *last = NULL;
void insert(int x){
if(first==NULL){
first = (Number*)malloc(sizeof(Number));
first->x=x;
first->next = NULL;
temp=first;
}
else{
last = (Number*)malloc(sizeof(Number));
last->x = x;
last->next = NULL;
temp->next =last;
temp=last;
}

}
void printList(){
Number *hold = first;
while(hold!=NULL){
printf("n%dn",hold->x);
hold = hold->next;
}
}

int main(){
int size;
printf("Enter size: ");
scanf("%d",&size);
printf("Enter value:n");

for(int i=0;i<size;i++){
int x;
scanf("%d",&x);
insert(x);
}
printList();
}

这是一些示例输出:

Enter size:5
Enter value:
1
2
3
4
5
1
2
3
4
5

最新更新