简体   繁体   English

malloc时指针之间的区别

[英]Difference between pointers when malloc

I usually make myself a struct and I allocate memory for the struct and sometimes for buffers inside the struct. 我通常将自己构造为一个结构,并为该结构分配内存,有时还为该结构内部的缓冲区分配内存。 Like so: 像这样:

typedef struct A
{
  char *buffer;
  int size;
} A;

Then when I malloc for the struct I do this. 然后,当我为结构体分配内存时,我就这样做了。 (I learned not to cast the malloc return here on SO.) (我学会了不在此处将malloc返回转换为SO。)

X X

A *a = malloc(sizeof(a));
a->buffer = malloc(10*sizeof(a->buffer));

What is the difference between X and Y this? X和Y this有什么区别?

Y ÿ

 A *a = malloc(sizeof(*a));
 a->buffer = malloc(10*sizeof(a->buffer));

They seem to be doing the same thing. 他们似乎在做同样的事情。

Neither is correct, the second one doesn't even compile. 都不正确,第二个甚至不编译。

You want either of these: 您需要以下任何一个:

A * a = malloc(sizeof(A));    // repeat the type

// or:

A * a = malloc(sizeof *a);    // be smart

Then: 然后:

a->size = 213;
a->buffer = malloc(a->size);

you should typecast it (A *) because calloc or malloc return void *. 您应该进行类型转换(A *),因为calloc或malloc返回void *。

A *a=(a*)malloc(sizeof(A));

suppose you want to allocate memory for buffer for 10 characters 假设您要为缓冲区分配10个字符的内存

a->buffer=(char *)malloc(sizeof(char)*10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM