解决C语言‘无类型参数列表仅允许在函数定义中’错误与函数问题
解决C语言中"a parameter list without types is only allowed in a function definition"错误
问题根源
- 函数调用位置错误:你把
searchStudentById(st,n);和displayStudent(st,n);写在了main()函数的闭合大括号}之后,属于全局代码区。编译器会误将这两行识别为函数定义,但代码里没有参数类型声明,因此触发报错。 - 缺少函数原型声明:C语言中,如果函数定义在调用代码之后,必须提前声明函数原型,否则编译器无法识别函数的参数和返回值类型,会触发隐式声明警告。
修复步骤
- 调整函数调用位置:将两个函数调用移到
main()函数内部,放在学生信息输入循环之后、main()结束之前。 - 添加函数原型声明:在
main()函数之前(或结构体定义之后)声明两个函数的原型。 - 修复其他代码细节:
fflush(stdin)属于标准C未定义行为,改用getchar()循环清理输入缓冲区的换行符。scanf("%s",&(st+i)->name)中,name是数组名本身就是指针,无需加&,改为scanf("%s", (st+i)->name)。- 新增
free(st)释放动态分配的内存,避免内存泄漏。
修复后的完整代码
//Seach by id #include <stdio.h> #include <stdlib.h> struct student //ten cau truc { int id; char name[50]; float marks; }; // 声明函数原型 void displayStudent(struct student *st, int n); void searchStudentById(struct student *st, int n); struct student *st; int main(){ int i,n; printf("\nBan muon luu bao nhieu sv: "); scanf("%d",&n); //cap phat bo nho dong cho struct st = (struct student*)malloc(n*sizeof(struct student)); for(i =0; i< n; i++){ //input information printf("\nEnter student information "); printf("\n--------------------------"); printf("\nStudent id: "); scanf("%d",&(st+i)->id);//scanf("%d",&st[i].id); // 清理输入缓冲区的换行符 while(getchar() != '\n'); printf("\nStudent name:"); scanf("%s", (st+i)->name); printf("\nStudent Marks: "); scanf("%f",&(st+i)->marks); } // 移到main函数内部的函数调用 searchStudentById(st,n); displayStudent(st,n); // 释放动态内存 free(st); return 0; } void displayStudent(struct student *st, int n){ int i; for(i=0; i<n; i++){ printf("\nId: %d, name: %s, Marks: %f",(st+i)->id, (st+i)->name, (st+i)->marks ); } } void searchStudentById(struct student *st, int n){ int search; int i; printf("\nNhap id sv can tim: "); scanf("%d",&search); for(i=0; i<n; i++){ if((st+i)->id==search){ printf("\nId: %d, name: %s, Marks: %f",(st+i)->id, (st+i)->name, (st+i)->marks ); } } }
内容的提问来源于stack exchange,提问作者Tran Vu Minh Ngoc Aptech HN
相关产品推荐
相关产品推荐

