I would like to copy a structure from an another structure like this:
#include <stdio.h>
#include <stdlib.h>
struct foo_struct{
int foo;
char *str;
};
static void foo(struct foo_struct *, struct foo_struct *);
void main(void) {
int i;
struct foo_struct *test = malloc(sizeof(struct foo_struct) * 5);
struct foo_struct *cpy_struct = NULL;
foo(test, cpy_struct);
cpy_struct->foo = 20;
//printf("%d\n", cpy_struct.foo);
free(test);
}
static void foo(struct foo_struct *test, struct foo_struct *cpy){
int i;
for(i = 0; i < 5; i++)
test[i].foo = i;
cpy = &test[2];
}
But, when I modify this entry: cpy_struct->foo = 20;
, I had a segmentation fault.
When I didn't use the pointer in struct foo_struct cpy_struct
, I modify my entry, but not a original structure:
struct foo_struct cpy_struct = {0};
foo(test, &cpy_struct);
cpy_struct.foo = 20;
printf("%d\n", cpy_struct.foo); /* Display 20 */
printf("%d\n", test[2].foo); /* Display 2 */
/* ... */
static void foo(struct foo_struct *test, struct foo_struct *cpy){
int i;
for(i = 0; i < 5; i++)
test[i].foo = i;
*cpy = test[2];
}
How can I copy this struct to update the value in specific structure ?
Thank you.