从C中的Structs开始

时间:2017-04-06 02:26:58

标签: c pointers struct

每次我尝试编译以下代码时,都会遇到大量错误。 有没有人看到我用C程序忽略的任何明显的事情。任何帮助,将不胜感激。 头文件structures.h也附加了。

这是structures.cc文件

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

void getOnePerson(person_t *p) {
char *name;
char *ssn;
int *year;

printf("Enter full name: ");
scanf("%s", &name);
p.name = &name;
printf("\nEnter ssn: ");
scanf("%s", &ssn);
p.ssn = &ssn;
printf("\nEnter year of birth: ");
scanf("%d", year);
p.yearOfBirth = &year;

}

void printOnePerson(person_t t1) {
char *name = t1.name;
char *ssn = t1.ssn;
int year = t1.yearOfBirth;
printf("%s", &name);
printf(":");
printf("%s", &ssn);
printf(":");
printf("%p", &year);
printf("\n");

}

void getPeople(person_t peoples[], int people) {
for (int a = 0; a < people; a++) {
    getOnePerson(peoples[a]);
}
}

void printPeople(person_t peoples[], int people) {
for (int p = 0; p < people; p++) {
    peoples[p];
}
}

这是structures.h文件

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

#define NAME_SIZE 80
#define SSN_SIZE 13
#define NUM_PEOPLE 10

typedef struct{
char name[NAME_SIZE];
char ssn[SSN_SIZE];
int yearOfBirth;
}person_t;

void getOnePerson(struct person_t *p);
void printOnePerson(struct person_t p);
void getPeople(struct person_t peoples[], int people);
void printPeople(struct person_t peoples[], int people);

1 个答案:

答案 0 :(得分:1)

头文件中的函数声明不正确。

您引用了struct person_t类型的一个或多个参数,但没有这种类型。有一个名为person_t的类型,因此请更改函数原型以使用它。

void getOnePerson(person_t *p);
void printOnePerson(person_t p);
void getPeople(person_t peoples[], int people);
void printPeople(person_t peoples[], int people);

您的获取和打印功能也有几个问题。在这两种情况下,您都使用中间变量来读取/写入不必要的值:

void getOnePerson(person_t *p) {

    printf("Enter full name: ");
    scanf("%s", p->name);
    printf("\nEnter ssn: ");
    scanf("%s", p->ssn);
    printf("\nEnter year of birth: ");
    scanf("%d", &p->yearOfBirth);

}

void printOnePerson(person_t t1) {

    printf("%s", t1.name);
    printf(":");
    printf("%s", t1.ssn);
    printf(":");
    printf("%d", t1.yearOfBirth);
    printf("\n");

}