我正在尝试理解在使用多级指针时何时需要使用malloc。例如,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
typedef struct {
char first[10];
char last[10];
} Person;
Person *p;
p = malloc(sizeof(Person));
strcpy(p->first, "John");
strcpy(p->last, "Doe");
printf("First: %s Last:%s\n", p->first, p->last);
return 0;
}
在这个第一个版本中,我使用
Person *p
并且只使用 malloc
来为类型 Person
分配空间。在第二个版本中,我将会把 Person *p
改为 Person **p
。#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
typedef struct {
char first[10];
char last[10];
} Person;
Person **p;
*p = malloc(sizeof(Person));
strcpy((*p)->first, "John");
strcpy((*p)->last, "Doe");
printf("First: %s Last:%s\n", (*p)->first, (*p)->last);
return 0;
}
我仍然只使用一个
malloc
即可,即使现在有另一个指针。在这第三个版本中,我将使用
Person ***p
。#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
typedef struct {
char first[10];
char last[10];
} Person;
Person ***p;
*p = malloc(sizeof(void));
**p = malloc(sizeof(Person));
strcpy((**p)->first, "John");
strcpy((**p)->last, "Doe");
printf("First: %s Last:%s\n", (**p)->first, (**p)->last);
return 0;
}
我的问题:
1)为什么在第三个版本中需要为**p
分配空间,但不需要为*p
分配空间?它们都是指向指针的指针?
2)另外,在第二个或第三个版本中,为什么我不需要为p
分配空间?
3)在第三个版本中,为*p
分配的正确大小是多少?在我的64位Mac上,sizeof(void)
为1,sizeof(void*)
为8,两者似乎都可以工作,但哪一个是正确的?
p
。你的代码是错误的。 - Amitwarning: ‘p’ is used uninitialized in this function [-Wuninitialized] *p = malloc(sizeof(Person));
- loginnmalloc(sizeof(Person*));
而不是malloc(sizeof(void*));
,因为你已经知道要使用的类型。这并不会改变计算机方面的任何东西,但可以使代码更清晰。 - loginn