[英]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
的地址。 對於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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.