简体   繁体   English

如何在C中复制结构数组

[英]How to copy array of struct in C

I have defined struct like 我已经定义了像

typedef struct {
    char *oidkey;
    int showperf;
    char oidrealvalue[BUFSIZE];
    char *oidlimits;
} struct_oidpairs;

and I have array of struct 我有数组的结构

 struct_oidpairs b[] ={{.....},....}

and I want to copy it to new struct array a[] 我想将其复制到new struct array a[]

please help 请帮忙

像这样:

memcpy(dest, src, sizeof(struct) * sizeof(src));

Your struct contains pointers as data members, this means you will have to roll out your own copy function that will do something sensible with the pointers. 您的结构包含指针作为数据成员,这意味着您将必须推出自己的复制函数,该函数将对指针做出明智的选择。 memcpy only works is all the data related to the struct is stored in the struct. memcpy仅适用于与该结构相关的所有数据都存储在该结构中。

For real copy of the contents, follow Sjoerd 's answer and then: 对于内容的真实副本,请遵循Sjoerd的回答,然后:

for (i = 0; i < sizeof(src); i++)
{
    if (src[i].oidkey != NULL)
    {
        dest[i].oidkey = malloc(strlen(src[i].oidkey) + 1);
        strcpy(dest[i].oidkey, src[i].oidkey);
    }

    if (src[i].oidlimits != NULL)
    {
        dest[i].oidlimits = malloc(strlen(src[i].oidlimits) + 1);
        strcpy(dest[i].oidlimits, src[i].oidlimits);
    }
}

You may consider memcpy if you are interested in speed. 如果您对速度感兴趣,可以考虑使用memcpy。

Update: 更新:

  • Following harper 's code, I updated the code to check NULL pointers 按照harper的代码,我更新了代码以检查NULL指针
  • This is a quoted note from gordongekko : 这是gordongekko的引文

    This solution will crash if oidkey or oidlimits are != NULL and not '\\0' -terminated means not initialized 如果oidkeyoidlimits!= NULL且不是'\\0' oidlimits终止意味着未初始化,则此解决方案将崩溃

Makes NOT a deep copy: 不制作深层副本:

struct_oidpairs b[] = {...};
size_t len = sizeof b/sizeof*b;
struct_oidpairs *a = malloc(sizeof b);

if( !a ) /* ERROR handling */

memcpy( a, b, sizeof b );
...
free( a );

or 要么

while( len-- )
  a[len] = b[len];
...
free( a );

maybe using : 也许使用:

for(int i=0; i<b.size() ;i++) 
//I am not sure if this is the correct name for the size function
{
a[i]=b[i];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM