Let's say I have this struct
in ANSI C:
typedef struct _point
{
float x;
float y;
} Point;
and this function to create this struct
:
Point createpoint(float x, float y)
{
Point p;
p.x = x;
p.y = y;
return p;
}
This allows me to create a struct
with this function i.e:
int main()
{
Point pointOne = createpoint(5, 6);
Point pointTwo = createpoint(10, 4);
float distance = calculatedistancefunc(pointOne, pointTwo);
/* ...other stuff */
return 0;
}
Someone told me that this code is not valid, because the struct
does not get malloc
'd in the createpoint(float x, float y)
function before it gets returned, and that the struct
will be deleted.
However, when I use my struct
like this, it doesn't seem to get deleted.
So my question is:
do I have to malloc
this struct
, and why? / why not?
This tells the compiler how big our struct is and how the different data items (“members”) are laid out in memory. But it does not allocate any memory. To allocate memory for a struct, we declare a variable using our new data type.
malloc allocates sizeof(struct node) bytes, and returns a void pointer to it, which we cast to struct node *. Under some conditions malloc could fail to allocate the required space, in which case it returns the special address NULL.
Example: Dynamic memory allocation of structs In the above example, n number of struct variables are created where n is entered by the user. To allocate the memory for n number of struct person , we used, ptr = (struct person*) malloc(n * sizeof(struct person));
The typedef statement itself allocates no memory. A variable declaration is required to allocate storage space for a structured data object.
Whatever you are doing is entirely correct. The statement -
return p;
in the function returns a copy of the local variable p
. But if you want the same object that was created in the function, then you need to malloc
it. However, you need to free
it later.
Point createpoint(float x, float y)
{
Point p;
p.x = x;
p.y = y;
return p;
} // p is no longer valid from this point. So, what you are returning is a copy of it.
But -
Point* createpoint(float x, float y)
{
Point *p = malloc(sizeof(Point));
p->x = x;
p->y = y;
return p;
}// Now you return the object that p is pointing to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With