任何变量的指针大小都是一样大小的空间,例如在64位机中是4个字节,在32位机中是2个字节。
而我们分配一个地址,就比如
力扣145题https://leetcode-cn.com/problems/binary-tree-postorder-traversal/solution/er-cha-shu-de-hou-xu-bian-li-by-leetcode-solution/
该题其中一句:
int *matrix = malloc(sizeof(int) * 2001);
给res这个指针分配了2001的int大小的空间,实际上就是给这里分配了可以装下2001个int类型变量的空间, 并且空间的首地址分配为res。
虽然分成了块,但是实际上空间是连续的,会意即可。
接下来,我们插入一个程序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node
{
char aa[10];
}Node;
int main()
{
Node* fat = (Node*)malloc(sizeof(Node*));
strcpy(fat->aa, "aaa");
printf("%s", fat->aa);
}
有什么问题呢,我们看到
Node* fat = (Node*)malloc(sizeof(Node*));
Node*表示分配的是Node*(也就是指针4字节)这么大的空间,
实际上我们需要的是Node这么大的空间分给fat这个指针。