简体   繁体   English

在函数C中将Struct复制到Pointer数组

[英]Copying Struct to a Pointer array in a function C

i have a huge problem allocating memory in C 我在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) 这样做的目的是在函数(主要)中使用t

many thanks :D 非常感谢:D

Your memcpy calls are incorrect. 您的memcpy电话不正确。

In the expression &(*t[0]) , the array index has top precedence, followed by the pointer indirection. 在表达式&(*t[0]) ,数组索引具有最高优先级,其后是指针间接寻址。 So with explicit parenthesis it looks like &(*(t[0])) . 因此,使用显式括号,它看起来像&(*(t[0]))

So it first tries to array subscript t , which is the address of t in main. 因此,它首先尝试对下标t进行数组, t是main中t的地址。 In the case of t[0] it still works, but t[1] references something past that variable, invoking undefined behavior. 对于t[0]它仍然有效,但是t[1]引用了超出该变量的内容,从而调用了未定义的行为。 You want the array index of what t points to, which is (*t)[i] . 您需要t指向的数组索引,即(*t)[i]

So the memcpy calls should be: 因此,memcpy调用应为:

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 . 整个var1复制到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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM