C中要求的非标量类型

时间:2013-11-01 15:27:45

标签: c

当我尝试编译此代码时,出现错误:请求转换为非标量类型。这个错误提到了行:

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);
 }

}

5 个答案:

答案 0 :(得分:1)

func的原型说:

void func(struct student record); 

应该是:

void func(struct student record[]);

答案 1 :(得分:1)

这是因为你有相互冲突的函数声明。

void func(struct student record[])

相当于

void func(struct student * record)

但你最初的声明是

void func(struct student record); 

答案 2 :(得分:1)

当你宣布这个功能时,你会这样做:

void func(struct student record);

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

struct student record[2];

当您确定定义为

 void func(struct student record[]) {

到那时为时已晚,无论后来的定义如何,编译器都会接受声明。

在声明中添加[]:

void func(struct student record[]);

答案 3 :(得分: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);
      }

 }

答案 4 :(得分:0)

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

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

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

void func(struct student record[]);