C语言是一种非常低级的语言,因此您需要决定如何处理每个字段。
在您的情况下,您需要确定什么是name
,谁拥有指向的数据,并适当地编码,可能类似于:
typedef struct person_st {
char* name; // malloc-ed string
int age;
} Person;
// allocate a Person of given name and age
Person* make_person(const char* n, int a) {
if (!n || a<0) return NULL;
Person* p = malloc(sizeof(Person));
if (!p)
perror("malloc Person"), exit(1);
p->name = strdup(n);
if (!p->name)
perror("strdup Person"), exit(1);
p->age = a;
return p;
}
// destroy a Person and the data inside
void destroy_person(Person*p) {
if (!p) return;
free (p->name);
free (p);
}
// read and allocate a Person
Person* input_person(FILE*f) {
if (!f) return NULL;
char name[104];
int age;
memset (name, 0, sizeof(name));
age = 0;
if (fscanf(f, " %100[A-Za-z] %d", &name, &age)<2)
return NULL;
return make_person(name, age);
}
具有调用者input_person
应destroy_person
适当调用的约定。
我可能误解了你的问题。您想简单地编写一个可变参数函数(与输入或输出无关)吗?然后小心使用<stdarg.h>
header。请注意,可变参数函数在 C 中的类型很差。使用 GCC,您可以提供标记函数属性,您甚至可以自定义 GCC,例如使用MELT来添加一些类型检查。