[英]C: copying struct/array elements
I have a file in a known format and I want to convert it to a new format, eg.: 我有一个已知格式的文件,我想将其转换为新格式,例如:
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];
Problem: after filling 'old' with the data I don't know how to copy its content to 'new'. 问题:用数据填充“旧”后,我不知道如何将其内容复制到“新”。 If I do
如果我做
new[0].name = old[0].name;
new[0].data = old[0].data;
I get a compile error about assigning char * to char[128] (struct foo * to struct foo[16], respectively). 我收到关于将char *分配给char [128](分别将struct foo *分配给struct foo [16])的编译错误。
I tried a solution I found via Google for the string part: 我尝试了通过Google针对字符串部分找到的解决方案:
strcpy (new[0].name, old[0].name);
new[0].data = old[0].data;
but I have no idea how to handle the struct. 但我不知道如何处理该结构。 Seems I lack basic understanding of how to handle arrays but I don't want to learn C - I just need to complete this task.
似乎我对如何处理数组缺乏基本的了解,但是我不想学习C-我只需要完成此任务即可。
If you don't want to learn C, you should be able to read the old file format in any language with a half-decent IO library. 如果您不想学习C,则应该可以使用任何具有半透明IO库的语言阅读旧文件格式。
To complete what you're trying to do in C, you could use memcpy. 为了完成您要在C中完成的工作,可以使用memcpy。
So instead of: 所以代替:
new[0].data = old[0].data;
Use 采用
memcpy(new[0].data, old[0].data, sizeof(foo) * 16);
You can also wrap the C arrays in a struct
. 您也可以将C数组包装在
struct
。 Then copying elements will copy the array automatically. 然后,复制元素将自动复制数组。
typedef struct {
char name[100];
} name_array_t;
struct {
name_array_t name_struct;
...
} x;
struct {
name_array_t name_struct;
... other members ...
} y;
x.name_struct = y.name_struct;
(too obvious solution may be) (解决方案可能太明显了)
As we are dealing with the array, we can not do this kind of operation 当我们处理数组时,我们无法执行此类操作
new.name = old.name; new.name = old.name;
so i suppose you have to write a function 所以我想你必须写一个函数
void Function (char *name , struct new_format *new ); void Function(char * name,struct new_format * new); where you need to assign charecter one by one.
您需要一个一个地分配字符。
Obviously you will Call like this : Function (old.name , &new) 显然,您将这样调用:Function(old.name,&new)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.