i have a huge problem allocating memory in C
i have this struct
typedef struct{
int x;
int y;
}T;
i want to create a function that dynamically adds a structs to a pointer. something like:
int main()
{
T* t;
f(&t);
free(t);
}
up to this point i think everything is ok, now the function is where i get lost
void f(T** t)
{
T t1;
T t2;
T t3;
//first i malloc
*t=malloc(sizeof(T)*T_MAX_SIZE);//i want another function to make the array bigger, but this is not as important as the problem
t1.x=11;
t1.y=12;
t2.x=21;
t2.y=22;
t3.x=31;
t3.y=32;
//now i want to copy the values from t1,t2,t3 to t[0],t[1],t[2]
memcpy(&(*t[0]),&t1,sizeof(T));
memcpy(&(*t[1]),&t2,sizeof(T));
memcpy(&(*t[2]),&t3,sizeof(T));
}
i do not know the correct way of copying these structs.
the point of doing this is to use t out of the function (in the main)
many thanks :D
Your
memcpy
calls are incorrect.In the expression
&(*t[0])
, the array index has top precedence, followed by the pointer indirection. So with explicit parenthesis it looks like&(*(t[0]))
.So it first tries to array subscript
t
, which is the address oft
in main. In the case oft[0]
it still works, butt[1]
references something past that variable, invoking undefined behavior. You want the array index of whatt
points to, which is(*t)[i]
.So the memcpy calls should be:
You don't need any copy functions to assign one structure to another - you simply equate them. So if you have
the whole of
var1
is copied tovar2
. Amending your (simplified) program:Program output: