Question

malloc isn't allocating the memory requested in the function. I've tried searching on another malloc related questions/google, and I think what I wrote is supposed to function. edit:~~~~ is filler code which really isn't supposed to be relevant to the problem =d

    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>

    typedef struct {

            int x;
            int y;        

    } Coordenada;

    int calculaCaminho(~~~~~Coordenada **posicoes) {
            int tam = 5;
    ~~~~

            *posicoes = (Coordenada*)malloc(tam*sizeof(Coordenada));

            //I can't access posicoes[k]->y or posicoes[k]->x for whatever value of k that was in the  
            //range of tam
    ~~~~


    return(~~~~);

    }
    main() {
    ~~~~      
            Coordenada *posicoes;
            npassos = calculaCaminho(~~~~, &posicoes);
    ~~~~
    }

Any ideas?

Was it helpful?

Solution

*posicoes = (Coordenada*)malloc(tam*sizeof(Coordenada));

After that, you could access (*posicoes)[k].x, but not posicoes[k]->x. If you use a temporary pointer for a moment, you'll notice it immediately:

Coordenada * ptr = (Coordenada*) malloc(tam*sizeof(Coordenada));

*posicoes        = ptr;
ptr[k].x         = 1; // ok
(*posicoes)[k].y = 2; // ok, same as ptr[k].y = 2;

// posicoes[k]->x = 0; // NOT ok

OTHER TIPS

//i cant access posicoes[k]->y or posicoes[k]->x for whatever value of k that was in the
//range of tam

You should access them as follows :

  posicoes[0][k].y ....

or

  (*posicoes)[k].y ....

(*posicoes) and posicoes[0] will give you access to the first element of allocated memory. After that you can access elements by their index relatively to first element..

You can access x and y like mentioned here..

*posicoes = (Coordenada*)malloc(tam*sizeof(Coordenada));
for(int k = 0 ; k < tam ; k++)
{
    (*posicoes)[k].x = k;
    (*posicoes)[k].y = 10*k;
}

and the same can be access in main like:

for(int k = 0 ; k < 5 ; k++)
{               
    //print ..  posicoes[k].x 
    //print ..  posicoes[k].y 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top