1

当我尝试编译此代码时,出现错误:转换为请求的非标量类型。此错误涉及以下行:

func( record);

我可以知道我的代码有什么问题吗?

#include <stdio.h>
#include <string.h>

struct student 
{
 int id;
 char name[30];
 float percentage;
};
void func(struct student record); 

int main() 
{

 struct student record[2];
 func( record);
 return 0;
 }     

 void func(struct student record[]) {
 int i;
 record[0].id=1;
 strcpy(record[0].name, "lembu");
 record[0].percentage = 86.5;


 record[1].id=2;
 strcpy(record[1].name, "ikan");
 record[1].percentage = 90.5;


 record[2].id=3;
 strcpy(record[2].name, "durian");
 record[2].percentage = 81.5;

 for(i=0; i<3; i++)
 {
     printf("     Records of STUDENT : %d \n", i+1);
     printf(" Id is: %d \n", record[i].id);
     printf(" Name is: %s \n", record[i].name);
     printf(" Percentage is: %f\n\n",record[i].percentage);
 }

}
4

5 回答 5

1

你的原型func说:

void func(struct student record); 

它应该是:

void func(struct student record[]);
于 2013-11-01T15:29:57.030 回答
1

这是因为您有冲突的函数声明。

void func(struct student record[])

相当于

void func(struct student * record)

但你最初的声明是

void func(struct student record); 
于 2013-11-01T15:30:07.290 回答
1

当您声明该功能时,您可以这样做:

void func(struct student record);

但是当你去使用它时,你正在传递一个

struct student record[2];

虽然您确实将 at 定义为

 void func(struct student record[]) {

到那时为时已晚,编译器接受声明,不管后面的定义如何。

在声明中添加 []:

void func(struct student record[]);
于 2013-11-01T15:30:39.080 回答
0

发生错误是因为编译器在匹配 的实际参数和形式参数时无法从student *to转换:studentfunc

在函数原型中,参数以 type 声明student。在定义中,它被声明为一个数组,在 C 中它衰减为一个指针。

修复函数原型,使其准确地声明您想要的内容:

void func(struct student record[]); 
于 2013-11-01T15:40:08.980 回答
0

我做了一些改变

 void func(struct student record[]); 

 int main() 
 {
     struct student record[3];

完整代码:

 #include <stdio.h>
 #include <string.h>

 struct student 
 {
     int id;
     char name[30];
     float percentage;
  };
 void func(struct student record[]); 

 int main() 
 {
     struct student record[3];
     func( record);
     return 0;
 }     

 void func(struct student record[]) {
     int i;
     record[0].id=1;
     strcpy(record[0].name, "lembu");
     record[0].percentage = 86.5;


     record[1].id=2;
     strcpy(record[1].name, "ikan");
      record[1].percentage = 90.5;


      record[2].id=3;
      strcpy(record[2].name, "durian");
      record[2].percentage = 81.5;

      for(i=0; i<3; i++)
      {
          printf("     Records of STUDENT : %d \n", i+1);
          printf(" Id is: %d \n", record[i].id);
          printf(" Name is: %s \n", record[i].name);
          printf(" Percentage is: %f\n\n",record[i].percentage);
      }

 }
于 2013-11-01T15:37:58.527 回答