簡體   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