zeejan
zeejan

Reputation: 285

Questions about malloc

Can someone explain these portion of code to me please? Correct me if I am wrong.

int *longest = malloc(sizeof(int)); 
*longest =0;

Does this mean:

  1. Return a pointer points to the beginning of a memory block whose size is 4 byte (for 32bit machine)? Why not just write malloc(4)?
  2. For the second line, does it mean that longest is a pointer of 4 byte block, start at 0?

Upvotes: 2

Views: 168

Answers (1)

  1. Yes, it gets exactly enough memory for one int. You should avoid explicitly assuming a given size - it makes it a nightmare to port to other platforms in the future. You spotted it yourself - sizeof(int) won't always be 4 everywhere.

  2. No, this assigns the value 0 to the newly allocated memory, which was pointed to by longest. The * here is the dereference operator, it informally says "I want to work with the thing this pointer points to".

Upvotes: 6

Related Questions