這是相當簡單的,聲明一個指向struct,然後與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.
您需要先爲結構分配空間。使用'malloc()' – Haris