PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

use of calloc()

ok, I am trying to learn how to program for the ppc and I could use some help. I have been reading through some tutorials on the net on programing. Ok, here is my question.

What is the exact purpose of calloc()

and

In this case, what does the following mean...

struct Misc
{
int x;
Misc y;
}*x;

void somefunction()
{
calloc(1, x);
}

(I think that is the correct syntax, but I am not positive. Oh wise programmers, please help).
calloc, and malloc are used to create buffers.

the first thing is a pointer to a struct *x, also looks like some sort of linked list maybe.. seeing how there is a reference to itself inside the struct..

i also didnt think calloc was used in that way.. i thought it was used more like

unsigned short *Buff = (unsigned short*)calloc(n1,n2);

n1 would be how many slots in the buffer and n2 s the size of each slot in bytes.. it may be reversed.
calloc and malloc are basically the same, the difference being that calloc will 'zero' the memory it allocates, where malloc will not.

the syntax is like this
Code:
TCHAR *szTemp = (TCHAR *)calloc(10, sizeof (TCHAR));


Things to keep in mind: When you allocate memory, you are getting allocated heap space and you MUST free it when you are done, like this.
Code:
freee (szTemp);


In your case you, it might look like this

Code:

typedef struct Misc_tag
{
int x;
Misc_tag *y;
}Misc FAR *LPMisc;

void somefunction()
{
LPMisc lpTemp;
lpTemp = (LPMisc)calloc(1, sizeof (Misc));
}


I modified it to make it more 'standard' notation wise.

Usually, you want to put your struct name with a _tag after it at the beginning of a typedef so that you can use it internally to the struct. Also, you seem to want to make a pointer version of the struct, which is accomplished with the FAR * (though you can just use *). In the code snippet, you would create a pointer to your struct, then calloc the space as that type, and it needs to be cast since calloc will return a void*.

Also, the params for calloc/malloc are, in order, the number of units to allocate, and the size of a unit. This is typical usage, you memory allocated it equal to number of units * unit size.