如何在终止线程之前将线程数据复制到数组?

时间:2019-02-15 23:59:49

标签: c linux multithreading struct copying

我正在尝试使用指向结构类型数组的指针引用线程结构的方法,从C中复制线程数据。

我试图使用“&”符号来获取结构数据,但这样做却出现了make错误。我想在终止该结构类型的线程之前复制整个结构的数据。

Person queue[300];
Person statsArray[300];
// the queue contains Person structs that have been given data already
//      within another method, prior to calling Leave().

typedef struct
{
struct timeval startChange;
struct timeval endChange;
struct timeval arrive;

int id;
int changingTime;
int storeTime;
int returning;
int numVisits;
int type;
int queuePos;
} Person;

void Leave(int queuePosition)
{
Person *aPerson = &queue[queuePosition];

statsArray[statsArrayIndex] = &aPerson;
statsArrayIndex++;
}

编译时,我收到“从类型'Person ** {aka struct **}'分配给类型'Person {aka struct}'的类型不兼容的错误”

1 个答案:

答案 0 :(得分:1)

根据错误消息,有问题的行是:

statsArray[statsArrayIndex] = &aPerson;

Person**分配给Person的位置。如果要复制每个struct元素,则可能需要:

statsArray[statsArrayIndex] = *aPerson;

请注意,对于大型结构数组而言,结构复制可能会非常昂贵。视您的程序而定,重新设计程序可能更好/可行,以便不进行复制而仅使用指向它的指针(例如,不要让线程破坏queue)。