【发布时间】:2015-10-15 12:10:11
【问题描述】:
我在 C 中分配内存时遇到了很大的问题
我有这个结构
typedef struct{
int x;
int y;
}T;
我想创建一个将结构动态添加到指针的函数。 类似:
int main()
{
T* t;
f(&t);
free(t);
}
到目前为止,我认为一切正常,现在功能是我迷路的地方
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));
}
我不知道复制这些结构的正确方法。
这样做的目的是在函数之外使用 t (主要)
非常感谢:D
【问题讨论】:
-
我正在删除 C++ 标签,因为它在这里无关紧要。
-
很抱歉,谢谢
-
@juanchopanza 已更改为相关标签,谢谢 :)
-
试试
(*t)[0] = t1;(*t)[1] = t2;(*t)[2] = t3;
标签: c pointers struct dynamic-memory-allocation