mallac Question

I’ve been looking at Mustata Bogdan’s quake 2 md2 loader and I can’t figure out why he uses this to allocate memory for the variables: mdl->skins = (md2_skin_t *) malloc(sizeof(md2_skin_t) * mdl->header.numSkins);

What is the “(md2_skin_t *)” for? I thought malloc was used without the “(md2_skin_t *)”

Can anyone help? Here is a code snipet:

typedef struct
{
int magic;
int version;
int skinWidth;
int skinHeight;
int frameSize;
int numSkins;
int numVertices;
int numTexCoords;
int numTriangles;
int numGlCommands;
int numFrames;
int offsetSkins;
int offsetTexCoords;
int offsetTriangles;
int offsetFrames;
int offsetGlCommands;
int offsetEnd;
} md2_header_t;

typedef char md2_skin_t[64];

typedef struct
{
float vertex[3];
float normal[3];
} md2_triangleVertex_t;

typedef struct
{
md2_header_t header;
md2_skin_t *skins;
md2_textureCoordinate_t *texCoords;
md2_triangle_t *triangles;
md2_frame_t *frames;
int *glCommandBuffer;
} md2_model_t;

mdl->skins = (md2_skin_t *) malloc(sizeof(md2_skin_t) * mdl->header.numSkins);
mdl->texCoords = (md2_textureCoordinate_t *) malloc(sizeof(md2_textureCoordinate_t) * mdl->header.numTexCoords);

malloc returns a void pointer you must cast it to the proper pointer type

So its simply the variable type.

Example:

int A;

A = (int *) malloc(sizeof(int) * 256);

kinda. int * is not void * so the accurate statement would be

int * x-malloc(sizeof(int))

ahhhhhhhhhhhhhhhhhh

i mean

int * x=(int *) malloc(sizeof(int))

Are you sure that is right?
malloc only returns a null pointer if it fails to allocate the memory.
I thought the cast was because malloc can’t “guarantee” it will return (other than NULL) the correct type…
but… (Unix man page)

Each of the allocation functions returns a pointer to space suitably aligned (after possible pointer coercion) for storage of any type of object.

gav

Originally posted by Gavin:
Are you sure that is right?
malloc only returns a null pointer if it fails to allocate the memory.

Mr. X said it returned a VOID pointer, not a NULL pointer. A NULL pointer is one that points to address 0. A void pointer is a pointer to an address, but has no associated type and can be cast to a pointer of any other type. The prototype for malloc looks like so…

void *malloc( size_t size );

[This message has been edited by Deiussum (edited 05-15-2001).]

doh.