在函数C中将Struct复制到Pointer数组 [英] Copying Struct to a Pointer array in a function C
问题描述
我在C中分配内存有很大的问题
i have a huge problem allocating memory in C
我有此结构
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.
这样做的目的是在函数
(主要)中使用t
the point of doing this is to use t out of the function (in the main)
非常感谢:D
推荐答案
您的 memcpy
通话不正确。
在表达式&(* t [0])
中,数组索引具有最高优先级,后跟指针间接。因此,使用显式括号,其外观类似于&(*(t [0]))
。
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]))
.
因此,它首先尝试对下标 t
(即 t
主要。在 t [0]
的情况下,它仍然有效,但是 t [1]
引用了超出该变量的内容,从而调用未定义的行为。您想要 t
指向的数组索引,即(* t)[i]
。
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]
.
因此memcpy调用应为:
So the memcpy calls should be:
memcpy(&((*t)[0]),&t1,sizeof(T));
memcpy(&((*t)[1]),&t2,sizeof(T));
memcpy(&((*t)[2]),&t3,sizeof(T));
这篇关于在函数C中将Struct复制到Pointer数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!