C:复制结构/数组元素

标签 c arrays struct copy

我有一个已知格式的文件,我想将其转换为新格式,例如:

struct foo {
    char            bar[256];
};

struct old_format {
    char            name[128];
    struct foo      data[16];
};

struct new_format {
    int             nr;
    char            name[128];
    struct foo      data[16];
};

static struct old_format old[10];
static struct new_format new[10];

问题:在用数据填充“旧”后,我不知道如何将其内容复制到"new"。如果我这样做

new[0].name = old[0].name;
new[0].data = old[0].data;

我在将 char * 分配给 char[128](分别将 struct foo * 分配给 struct foo[16])时遇到编译错误。

我尝试了通过 Google 为字符串部分找到的解决方案:

strcpy (new[0].name, old[0].name);
new[0].data = old[0].data;

但我不知道如何处理该结构。似乎我对如何处理数组缺乏基本的了解,但我不想学习 C - 我只需要完成这个任务。

最佳答案

如果您不想学习 C,您应该能够使用半正经的 IO 库读取任何语言的旧文件格式。

要完成您在 C 中尝试做的事情,您可以使用 memcpy。

所以代替:

new[0].data = old[0].data;

使用

memcpy(new[0].data, old[0].data, sizeof(foo) * 16);

关于C:复制结构/数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1513443/

相关文章:

c - 在 Julia 中声明 C void 指针的正确方法

c - "Process terminated with status -1073741510 (0 minute(s), 6 second(s))"

python - 有效地从 np 数组中删除零

javascript - 如何根据子属性将 JSON 排序到数组中

c# - Marshal.SizeOf 结构返回过多的数字

c - 错误 : invalid type argument of unary '*' (have 'int' )

c - 试图修复有关 ‘const’ 限定符的警告

c - 从数组进行简单的 unsigned long long 转换

c - #define 和声明有什么区别

ruby - Array() 应用于哈希?