将结构复制到函数 C 中的指针数组
Copying Struct to a Pointer array in a function C
我在 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
您的 memcpy
调用不正确。
在表达式&(*t[0])
中,数组索引具有最高优先级,其次是指针间接。所以有了明确的括号,它看起来像 &(*(t[0]))
。
所以它首先尝试数组下标t
,也就是t
在main中的地址。在 t[0]
的情况下它仍然有效,但 t[1]
引用了该变量之后的内容,调用未定义的行为。您想要 t
指向的数组索引,即 (*t)[i]
.
所以 memcpy 调用应该是:
memcpy(&((*t)[0]),&t1,sizeof(T));
memcpy(&((*t)[1]),&t2,sizeof(T));
memcpy(&((*t)[2]),&t3,sizeof(T));
您不需要任何复制函数即可将一个结构分配给另一个结构 - 您只需将它们等同起来。所以如果你有
T var1 = {1, 2};
T var2 = var1;
整个var1
被复制到var2
。修改您的(简化)程序:
#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;
}
程序输出:
Result 11 12
我在 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
您的 memcpy
调用不正确。
在表达式&(*t[0])
中,数组索引具有最高优先级,其次是指针间接。所以有了明确的括号,它看起来像 &(*(t[0]))
。
所以它首先尝试数组下标t
,也就是t
在main中的地址。在 t[0]
的情况下它仍然有效,但 t[1]
引用了该变量之后的内容,调用未定义的行为。您想要 t
指向的数组索引,即 (*t)[i]
.
所以 memcpy 调用应该是:
memcpy(&((*t)[0]),&t1,sizeof(T));
memcpy(&((*t)[1]),&t2,sizeof(T));
memcpy(&((*t)[2]),&t3,sizeof(T));
您不需要任何复制函数即可将一个结构分配给另一个结构 - 您只需将它们等同起来。所以如果你有
T var1 = {1, 2};
T var2 = var1;
整个var1
被复制到var2
。修改您的(简化)程序:
#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;
}
程序输出:
Result 11 12