我在 C 中有以下结构:
typedef struct
{
int age;
char name[20];
} Person;
在 main()
我有:
Person *person;
person->age = 21;
这会导致段错误,我已经尝试使用谷歌搜索,但我发现的资源没有将结构声明为指针。我需要将此结构声明为指针,以便将其传递给另一个函数。我将如何正确访问该结构的成员? (我还需要为 char
执行此操作)。
最佳答案
它相当简单,声明一个指向结构的指针,然后使用 malloc
进行分配并分配/复制值:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int age;
char name[20];
} Person;
void agingfunction (Person **p)
{
(*p)->age = 25;
}
int main (void) {
Person *p = malloc (sizeof *p);
if (!p) return 1;
p->age = 5;
strncpy (p->name, "Charles Darwin", 20);
printf ("\n %s is %d years old.\n", p->name, p->age);
agingfunction (&p);
printf ("\n %s is now %d years old.\n", p->name, p->age);
free (p);
return 0;
}
输出
$ ./bin/structinit
Charles Darwin is 5 years old.
Charles Darwin is now 25 years old.
关于c - 如何初始化指针指向的结构的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33229558/