Mike John
Mike John

Reputation: 818

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.)

X

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

What is the difference between X and Y this?

Y

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

They seem to be doing the same thing.

Upvotes: 0

Views: 194

Answers (2)

InvisibleWolf
InvisibleWolf

Reputation: 1017

you should typecast it (A *) because calloc or malloc return void *.

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

suppose you want to allocate memory for buffer for 10 characters

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

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477640

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);

Upvotes: 6

Related Questions