所以我有一个内部有数组的结构,如下所示:
struct struct1 {
unsigned char data1[32];
unsigned char data2[32];
char *id;
};第二个结构定义为
typedef struct
{
uint8_t id;
uint8_t data1[32];
uint8_t data2[32];
} struct2;已经包含数据的Struct1通过如下函数传递给我:
bool func1(struct struct1 * const struct1)我需要创建一个新的struct2,并将struct1中的所有数据传递给它。
我想我可以像这样分配指针
struct2 *new_struct;
new_struct->id = struct1->id;
new_struct->data1 = struct1->data1;
new_struct->data2 = struct1->data2;但是我猜C中的数组指针是不能改变的(或者至少这是我在阅读它时得到的)。
那么,如何创建一个新的struct2并将所需的数据从struct1传递给它呢?
发布于 2018-06-11 10:45:00
不能更改C中的
数组指针
没有“数组指针”这回事。要么你有一个数组,要么你有一个指针。
在本例中,data1和data2是数组,所以没有可以重新分配的指针。您唯一的选择是将存储在数组中的数据从一个结构复制到另一个结构。
您可以在相同类型的结构变量之间使用简单赋值(=),但在您的示例中,您具有不同的类型,因此需要分别复制每个成员。要做到这一点,最简单的方法是使用memcpy (来自<string.h>)。
#include <string.h>
// ...
struct2 new_struct;
new_struct.id = *struct1->id;
memcpy(new_struct.data1, struct1->data1, sizeof new_struct.data1);
memcpy(new_struct.data2, struct1->data2, sizeof new_struct.data2);备注:
new_struct在这里不是指针。在你的例子中,你引用了一个未初始化的指针,它有未定义的行为。struct1->id,因为struct2.id是一个单独的char,而不是一个指针。我想这就是你想要发生的事情吧。https://stackoverflow.com/questions/50789735
复制相似问题