我只是进入结构并为它们分配内存。现在我有一些开箱即用的示例代码,如下所示 "学习C The Hard Way">
struct Person {
char *name;
int age;
int height;
int weight;
};
struct Person *Person_create(char *name, int age, int height,
int weight)
{
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight = weight;
return who;
}
这就是我的理解。在函数*Person_create
中,指针*who
接收大小为 struct Person
的内存块的地址。 Struct Person
有 4 个成员、一个指向字符串的指针和三个整数。由于指针*who
是struct Person
类型,因此据我所知,它应该知道它具有这些成员。
现在我尝试用一些自己的代码创建类似的东西。不幸的是,我在尝试为即将到来的变量 int age
扫描 (( 整数时出现段错误。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#define STRINGLENGTH 30
struct Person {
char *name;
char *food;
int age;
float height;
};
struct Person *createPerson(FILE *file){
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->name = malloc(sizeof(who->name)*STRINGLENGTH);
who->food = malloc(sizeof(who->food)*STRINGLENGTH);
printf("What is the name of the person?n");
scanf("%29s",who->name);
fprintf(file,"Name:%sn",who->name);
printf("What food do you eat?n");
scanf("%29s",who->food);
fprintf(file,"Food:%sn",who->food);
printf("How old are you?n");
scanf("%d",who->age);
fprintf(file,"Age:%dn",who->age);
printf("Whats your height?n");
scanf("%f",who->height);
fprintf(file,"Height:%fn",who->height);
return who;
}
void freePerson(struct Person *who){
free(who->name);
free(who->food);
free(who);
}
int main(int argc, char *argv[]){
FILE *file;
if((file = fopen("person.txt","a")) == NULL){
perror(NULL);
return EXIT_FAILURE;
}
printf("Creating a person...n");
struct Person *newPerson = createPerson(file);
freePerson(newPerson);
fclose(file);
return EXIT_SUCCESS;
}
- 那么导致问题的区别是什么?
- 我也需要单独分配成员吗?
- 是因为变量已经在示例代码中设置了吗?
您会收到段错误,因为您没有传递年龄字段的地址。相反,您复制它是不确定的值,供scanf
视为地址。
一个简单的本地修复:
scanf("%d",&(who->age));
fprintf(file,"Age:%dn", who->age);
当我们讨论这个主题时,您为字符串分配的内存比您可能预期的要多得多。 sizeof(who->name)
是指针的大小,它不小于它指向的char
的大小。更重要的是,保证sizeof(char) == 1
.因此,字符串的分配可以完全简化:
who->name = malloc(STRINGLENGTH);