I have this structure:

typedef struct nodo{
    int dato;
    struct nodo *izq;
    struct nodo *der;
}nodo;
typedef struct nodo *avl;

I have this method:

void insertar(avl *r, int dato){
    if (*r==NULL){
    *r=(nodo*)malloc(sizeof(nodo));
    (*r)->dato=dato;
    (*r)->izq=NULL;
    (*r)->der=NULL;

All this code works perfectly. My question is about the line:

*r=(nodo*)malloc(sizeof(nodo));

Why I have to put * on the right side of the name of the type of data??
Why it doesn't work with:

*r=(*nodo)malloc(sizeof(nodo));

its just how the header file declared it. i tried changing the declaration of "atol(const char*)" to "atol(char)" in the stdlib header file. the program ran but it crashed after i typed in my input.

The (*nodo) is because malloc() is declared like so:

extern char * malloc();

so you must cast to nodo * to make the compiler happy.

Why I have to put * on the right side of the name of the type of data??
Why it doesn't work with:

*r=(*nodo)malloc(sizeof(nodo));

Because nodo is treated as a kind of type, like int , whereas r is a variable. So, having *nodo makes no sense; you wouldn't see something like *int either. I think the malloc either returns void * or char * , I can't remember which. Either way, you need to cast to the type you need, hence the (nodo *) part.

You could probably use new instead of malloc in this code. Also, are you sure about (*r)->izq = NULL ? it looks like it should be either (*r).izq = NULL or, more usually, r->izq = NULL ?

Anyway, hope that helps :0)

its just how the header file declared it. i tried changing the declaration of "atol(const char*)" to "atol(char)" in the stdlib header file. the program ran but it crashed after i typed in my input.

I think I'd go ahead and assume that it's NEVER a good idea to edit the standard header files! Just don't do it.

I think I'd go ahead and assume that it's NEVER a good idea to edit the standard header files! Just don't do it.

oh yeah, i learned my lesson.

Also, are you sure about (*r)->izq = NULL ? it looks like it should be either (*r).izq = NULL or, more usually, r->izq = NULL ?

Anyway, hope that helps :0)

OK, ignore that. I see what you've done there :0)

Because nodo is treated as a kind of type, like int , whereas r is a variable. So, having *nodo makes no sense; you wouldn't see something like *int either.

Cleared. I understand it now :icon_cheesygrin:
thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.