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 of t
in main. In the case of t[0]
it still works, but t[1]
references something past that variable, invoking undefined behavior. You want the array index of what t
points to, which is (*t)[i]
.
So the memcpy calls should be:
memcpy(&((*t)[0]),&t1,sizeof(T));
memcpy(&((*t)[1]),&t2,sizeof(T));
memcpy(&((*t)[2]),&t3,sizeof(T));
You don't need any copy functions to assign one structure to another - you simply equate them. So if you have
T var1 = {1, 2};
T var2 = var1;
the whole of var1
is copied to var2
. Amending your (simplified) program:
#include <stdio.h>
#include <stdlib.h>
#define T_MAX_SIZE 10
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;
}
int main(void) {
T* t;
f(&t);
printf ("Result %d %d\n", t[0].x, t[0].y);
free(t);
return 0;
}
Program output:
Result 11 12