Tuesday 15 February 2011

c - When is it necessary to allocate dynamic memory using malloc on pointers? -


I'm having difficulty understanding the malloc () function in C, more accurately when using it

When I declare a global structure like this indicator,

  struct position * currentPositionPtr;   

Do I need to use dynamic malloc to start using malloc? Or is it a good practice to allocate it to an indicator of the structure later, such as when it is necessary

  current PositionPtr = getPosition ();   

Where getPosition () returns an indicator on "indicator status".

What does getPosition () ?

If it returns a valid indicator for the struct state , then surely you do not need to assign memory to twice the structure. I hope your no look like this:

  struct status * getPosition () {struct position p = {x, y}; Return and p; }   

Because it will display undefined behavior (by returning a pointer to a block scope automated object) Generally, you instead of already malloc () Returns the pointer on the screen:

  struct position * getPosition () {struct position * p = malloc (sizeof (* P)); P-> x = 42; P-> Y = 1337; Return p; }   

Then, then you do not need to call additional at malloc () .

If, however, this is not a function to be said which is responsible for allocation, then, well ... it is a collar:

  zero getPosition ( Struct position * p) {p-> gt; X = 42; P-> Y = 1337; }   

And in the latter case you have to call it this way:

  struct position * p = malloc (sizeof (* p)) ; GetPosition (P);   

If the function returns you need your structure to survive, or

  struct position p; GetPosition (& amp; P);   

If you do not.

No comments:

Post a Comment