Search code examples
cpointersstructdynamic-memory-allocation

assigning values to a copied pointer in a function C


i have this:

typedef struct{
int x;
int y;
}T;
void f(T** t)
{
    T t1;
    *t=malloc(sizeof(T)*T_MAX_SIZE);
    t1.x=11;
    t1.y=12;
    (*t)[0] = t1;
}

and i want this to work moving a pointer, instead of using location, im not really sure where or whats the problem, code:

void f(T** t)
{
 T t1;
 T t2;
 T** copy=t;
 *t=malloc(sizeof(T)*T_MAX_SIZE);
 t1.x=11;
 t1.y=12;
 t2.x=21;
 t2.y=22;
 **copy=t1;
 copy++;
 **copy=t2;

}
int main()
{
 T* t;
 f(&t);
 printf("%i %i\n",t[0].x,t[1].x);
 free(t);
}

this is a continue of the following thread ->Copying Struct to a Pointer array in a function C

and this doesnt not work :/


Solution

  • Your level of indirection is wrong. it should be:

    void f(T** t)
    {
        T t1;
        T t2;
        T* copy = *t = malloc(sizeof(T)*T_MAX_SIZE);
        t1.x=11;
        t1.y=12;
        t2.x=21;
        t2.y=22;
        *copy=t1;
        copy++;
        *copy=t2;    
    }
    

    Your posted code is advancing to the "next" T* in a sequence of only a single element, namely that addressed by &t back in main(). There is no such "next" element, and thusly your code invokes undefined behavior. You're (un)lucky it didn't outright-crash.