-
quick malloc question
I jsut have a question concerning malloc and how exactly is best to use it.
I've created some variables for example:
Code:
typedef struct tagVector3{
float x,y,z;
}Vector3;
typedef struct tagSomething{
Vector3 *position;
}Something;
when creating the variable "Something" what I would normally do would malloc Something and then malloc the Vector3 variable "position" within it. I've never known if this is the correct way, but always had the nagging feeling it wasn't, so does anyone have an answer?
Hope this makes sense and thanks for any help,
H
-
Your code above declares two typedef aliases to structs, it doesn't actually create variables.
You could create an instance of the Something type with:
This wouldn't require a malloc except for the position inside:
Code:
foo.position = malloc(n * sizeof *foo.position);
Where n is the number of "Vector3" things you want to allocate for position to point to. Since it's a position, I'm imagining just one, but then you wouldn't have bothered with a pointer, would you.
If on the other hand, you declared a pointer to Something, you'd do:
Code:
Something *foo;
foo = malloc(sizeof *foo);
foo.position = malloc(sizeof *foo.position);
Of course, you'd check the return of malloc for NULL in each instance.
-
Well Something isn't a variable, it's a type (or more specifically a type alias for struct tagSomething)
So you need to create a variable
Something foo;
This in itself does not need a call to malloc, since it isn't a pointer.
It does however contain a pointer, so allocating memory for that is a good idea, like so
foo.position = malloc ( 100 * sizeof *foo.position );