链表代码报错:no matching function for call to 'number::number(void)' 求排查
链表代码报错:
no matching function for call to 'number::number(void)' 问题排查 尝试编写链表代码但无法正常运行,在为first和last指针调用malloc时出现错误:
no matching function for call to 'number::number(void)',代码如下:
#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(" %d ",hold->x); hold = hold->next; } } int main(){ int size; printf("Enter size: "); scanf("%d",&size); Number *hold = first; printf("Enter value: "); for(int i=0;i<size;i++){ int x; scanf("%d",&x); insert(x); } printList(); }
问题原因分析
- 核心错误:
malloc函数返回的是void*类型的内存地址指针,你错误地将其强制转换为Number(结构体值类型),而不是Number*(结构体指针类型)。指针变量只能存储地址,必须匹配指针类型的赋值。 - 次要错误:
printList函数中的printf语句格式错误,换行符应使用\n而非单独换行,这会导致编译失败或输出格式异常。
修正后的代码
#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){ // 修正:将malloc结果转为Number*指针类型 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的换行符格式 printf("%d\n", hold->x); hold = hold->next; } } int main(){ int size; printf("Enter size: "); scanf("%d", &size); printf("Enter values:\n"); for(int i=0; i<size; i++){ int x; scanf("%d", &x); insert(x); } printList(); return 0; }
额外说明
- 在C标准中,
void*可以隐式转换为其他指针类型,因此也可以省略(Number*)的强制转换,编译器会自动处理。 - 建议在程序结束前添加链表内存释放的逻辑,避免内存泄漏(遍历链表逐个调用
free即可)。
内容的提问来源于stack exchange,提问作者Rommel Bagasina
相关产品推荐
相关产品推荐

