C语言结构体数组编译错误求解:元素/形参类型不完整
C语言学生数据库编译错误修复与指针实现
错误成因分析
- 函数声明
accept和display写在了struct student定义之前,编译器处理函数声明时,还未识别struct student的完整结构,会将其判定为不完整类型,从而触发"array type has incomplete element type"等错误。 scanf("%s", &arr[i].name)中的&属于冗余操作:arr[i].name是字符数组名,本身就是指向数组首元素的指针,无需额外取地址。
修正后的基础版本代码
将结构体定义移至函数声明之前,同时移除冗余的&:
#include<stdio.h> // 先定义结构体,让编译器提前知晓struct student的完整类型 struct student { char name[15]; int rollno; float marks; }; // 此时函数声明可正常识别参数类型 void accept(int no, struct student arr[20]); void display(int no, struct student arr[20]); int main() { int no; printf("Enter the number of students: "); scanf("%d", &no); struct student arr[20]; accept(no, arr); display(no, arr); } void accept(int no, struct student arr[20]) { for(int i=0; i<no; i++) { printf("Enter the name of the student: "); scanf("%s", arr[i].name); // 移除多余的& printf("\nEnter the Roll No: "); scanf("%d", &arr[i].rollno); printf("\nEnter the marks: "); scanf("%f", &arr[i].marks); } } void display(int no, struct student arr[20]) { for(int i=0; i<no; i++) { printf("\nName: %s ", arr[i].name); printf("Roll No: %d ", arr[i].rollno); printf("Marks: %.2f", arr[i].marks); // 优化格式,提升可读性 } }
指针实现版本
C语言中数组作为函数参数时会自动退化为指向首元素的指针,因此可以直接用指针接收数组,写法更灵活(无需固定数组大小):
#include<stdio.h> struct student { char name[15]; int rollno; float marks; }; // 用指针接收数组,写为struct student *arr更直观 void accept(int no, struct student *arr); void display(int no, struct student *arr); int main() { int no; printf("Enter the number of students: "); scanf("%d", &no); struct student arr[20]; accept(no, arr); // 数组名直接传递,等价于&arr[0] display(no, arr); } void accept(int no, struct student *arr) { for(int i=0; i<no; i++) { printf("Enter the name of student %d: ", i+1); scanf("%s", arr[i].name); // 指针可通过下标访问,与数组用法一致 printf("Enter Roll No: "); scanf("%d", &arr[i].rollno); printf("Enter marks: "); scanf("%f", &arr[i].marks); printf("\n"); } } void display(int no, struct student *arr) { printf("\n--- Student List ---\n"); for(int i=0; i<no; i++) { printf("Student %d:\n", i+1); printf(" Name: %s\n", arr[i].name); printf(" Roll No: %d\n", arr[i].rollno); printf(" Marks: %.2f\n", arr[i].marks); } }
内容的提问来源于stack exchange,提问作者curiosity
相关产品推荐
相关产品推荐

