我试图在我的main()中声明我在单独文件中构建的结构,但出现错误:
error: storage size of 'phone' isn't known
这是main.c的代码:
#include "header.h"
int main(int argc, char **argv)
{
struct firstAndLast name;
struct contact phone;
struct address adr;
struct allInfo individual;
print_person(individual);
return 0;
}
这是我在其中编写结构的function.c文件:
#include "header.h"
struct firstAndLast
{
char firstName[20];
char lastName[20];
};
struct contact
{
int pNumber;
};
struct address
{
struct firstAndLast person;
struct contact phoneNumber;
char streetAddress[100];
char city[50];
char province[50];
char postalCode[10];
};
struct allInfo
{
struct address addr;
char occupation[50];
double salary;
};
void print_person(struct allInfo indiv)
{
printf("%s \n",indiv.addr.person.firstName);
}
这是header.h文件:
#ifndef nS
#define nS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct firstAndLast;
struct contact;
struct address;
struct allInfo;
void print_person(struct allInfo indiv);
#endif
我不确定为什么会收到此错误。我将所有函数都放在头文件中,并且对main.c和functions.c文件都使用#include“ header.h”,因此它应该识别出存在的结构。我在main()中声明结构的方式或在标题中列出结构的方式是否存在问题?我在代码中看不到任何错字,所以我真的迷路了,也不知道我在做什么错。
首先,您需要将完整的结构定义移到头文件中。
#pragma once
#ifndef nS
#define nS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct firstAndLast
{
char firstName[20];
char lastName[20];
};
struct contact
{
int pNumber;
};
struct address
{
struct firstAndLast person;
struct contact phoneNumber;
char streetAddress[100];
char city[50];
char province[50];
char postalCode[10];
};
struct allInfo
{
struct address addr;
char occupation[50];
double salary;
};
void print_person(struct allInfo indiv);
#endif
此外,请在使用每个变量之前对其进行初始化。
例如:
struct firstAndLast name;
strcpy(name.firstName, "firstNameA");
strcpy(name.lastName, "lastNameB");
struct contact phone;
phone.pNumber = 01234567;
struct address adr;
adr.person = name;
adr.phoneNumber = phone;
strcpy(adr.streetAddress, "ABC street");
strcpy(adr.city, "DEF city");
strcpy(adr.province, "GH");
strcpy(adr.postalCode, "12345");
struct allInfo individual;
individual.addr = adr;
strcpy(individual.occupation, "Occupation");
individual.salary = 1234.56;
print_person(individual);