tags:

views:

144

answers:

5

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[]

please help

+1  A: 

Something like this:

memcpy(dest, src, sizeof(struct) * sizeof(src));
Sjoerd
This will not work as expected if oidkey and oidlimits are dynamically allocated strings.
Oskar N.
It makes a shallow copy of the struct, thus it copies the *pointers*, not the contents of the strings.
Sjoerd
Yes as long as `oidkey` and `oidlimits` are constants and not subject to be changed in the copied version of the array AND both the source during the lifetime of the copied array
mmonem
How does this memcpy differ from struct copying `a[i]=b[i];` mentioned in the down voted answer (except for the b.size() part, of course)? If the array size is specified properly, wouldn't struct copying work similar to a shallow memcpy?
Amarghosh
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];
}
Ahmed
+2  A: 

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.

doron
+1  A: 
mmonem
You must check for NULL pointers in oidkey and oidlimits to avoid undefined behavior (i.e. page fault). You may consider strdup instead of malloc+strcpy to reduce code lines. And you may use strdup instead of malloc+strcpy to save code lines.
harper
your solution will crash if oidkey/oidlimits are !=NULL and not '\0'-terminated means not initialized.
@harper: `strdup` is not a standard function. In other words, there's no such function as `strdup` in C.
AndreyT
A: 

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 );