繁体   English   中英

函数返回结构时出错

[英]error with function returning a structure

这就是我想要做的:

我一直在研究我已经创建了一个结构的代码(在main中硬编码)然后我想要malloc空间用于两个结构(试着使用函数)。 然后将第一个结构中的所有数据复制到第二个结构中并打印新结构。

发生的错误是:我不明白这个错误意味着什么。

pointer.c:7: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
pointer.c:13: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token



#include <stdio.h>
#include <stdlib.h>
#include "pointer.h"
int rec = 0;

第7行

struct emp *create(int record){
emp *new_employees = malloc(sizeof(info) * (record+1));

return new_employees;   
}

第13行

struct emp *copy(emp *data, int record){
emp *new_employee = create(record+1);
int i;
for(i = 0; i<record;i++){
    new_employee.first = data.first;
    new_employee.last = data.last;
    new_employee.start_date = data.start_date;
    new_employess.sal = data.sal;
    data++;
}
return new_employee;
}


int main(void){
struct info employees;
employees.first = "FIRST";
employees.last = "LAST";
employees.start_date = "June-20th-2006";
employees.sal = 55555.55;
rec = rec+1;



}

头文件:

#include <string.h>
struct info {
char *first;
char *last;
char *start_date;
float sal;
} emp;

info不是类型, emp只是struct info类型的变量。 添加一个typedef(如果你想将emp作为一个类型):

typedef struct info {
    char *first;
    char *last;
    char *start_date;
    float sal;
} emp;

...或添加struct关键字。

struct info *create(int record);
struct info *copy(emp *data, int record);

emp是变量, info是类型。 因此,您应该在函数原型和正文中使用info而不是emp

像其他人说的那样,缺少一个typedef或者缺少一个struct info而不是emp 我错过了那一个:)

恕我直言,这些是您的代码中的两个明显错误。

emp *new_employees = malloc(sizeof(info) * (record+1));

类型的名称是struct info ,而不是info

但是更好的方法是:

emp * new_employees = malloc((record + 1)* sizeof * emp);

您必须定义如下函数:

struct emp *create()
struct emp *copy()

或者使用typedef将结构定义为数据类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM