先随便举个结构体的例子:
typedef struct {
int32_t width;
int32_t height;
}Buffer;//长和高两个值
创建一个结构体变量,如果不赋值,系统则会赋不可控的值。
Buffer a;
printf("------before init------\n");
printf("a->width : %d, \n", a.width);
printf("a->height : %d, \n", a.height);
/*
------before init------
a->width : 288953888,
a->height : 329,
*/
如果想要使用结构体指针的话,可以有两种方法创建初始化
1. 为b申请一块内存,在后续的操作中为其赋值,成功
//1
Buffer *b = (Buffer*)malloc(sizeof(Buffer));
b->width =1000;
printf("b->width : %d, \n", b->width);
2.向下文那样写会报错。因为将指针b指向空指针,并没有为其分配内存。需要把b指向一个地址
//2
Buffer *b = nullptr;
b->width =1000;//报错。因为将指针b指向空指针,并没有为其分配内存。需要把b指向一个地址
指针传参
下面的create 中,通过a->来赋值,而Create通过将a指向另一个
int32_t create(Buffer* a)
{
a->width = 960;
a->height = 540;
printf("in the function create, %d x %d\n",a->width,a->height);
return 0;
}
int32_t Create_by_malloc(Buffer* a)
{
Buffer *b = (Buffer*)malloc(sizeof(Buffer));
b->height = 1000;
b->width = 2000;
a = b;
printf("in the function Create_by_malloc, %d x %d\n",a->width,a->height);
return 0;
}
int main{
...
Buffer a;
printf("before init a: %d x %d\n", a.width,a.height);
create(&a);
printf("after create a: %d x %d\n", a.width,a.height);
Create_by_malloc(&a);
printf("after Create_by_malloc a: %d x %d\n", a.width,a.height);
}
从运行结果看,Create_by_malloc将其函数里的形参指向一个新的地址的时候并没有起到修改实参的作用。因为这个形参可以理解为拷贝一份指针,型参与实参地址相同,所以create可以通过修改指针地址所指向的内容