M
Michael
Hi all,
I want to copy a structure, but the only thing
I have is a pointer to it.
Whats good here? Because the structure contains no pointers,
but arrays and variables I thought of doing a memcpy:
#include <stdio.h>
#include <string.h>
struct test {
int a;
int b[2];
};
int main (void)
{
struct test t1, t2;
struct test *pt1;
pt1 = &t1;
t1.a = 1; t1.b[0] = 42; t1.b[1] = 173;
memcpy(&t2, pt1, sizeof(t2) );
printf ( "t1:a=%d, b_0=%d, b_1=%d\n", t1.a, t1.b[0], t1.b[1]);
printf ( "t2:a=%d, b_0=%d, b_1=%d\n", t2.a, t2.b[0], t2.b[1]);
return 0;
}
t2:a=1, b_0=42, b_1=173
It works, but I am a little confortable with this
solution. Would it be better to use a function, which
copy each variable?
t2:a=1, b_0=42, b_1=173
Thanks in advance
Michael
I want to copy a structure, but the only thing
I have is a pointer to it.
Whats good here? Because the structure contains no pointers,
but arrays and variables I thought of doing a memcpy:
#include <stdio.h>
#include <string.h>
struct test {
int a;
int b[2];
};
int main (void)
{
struct test t1, t2;
struct test *pt1;
pt1 = &t1;
t1.a = 1; t1.b[0] = 42; t1.b[1] = 173;
memcpy(&t2, pt1, sizeof(t2) );
printf ( "t1:a=%d, b_0=%d, b_1=%d\n", t1.a, t1.b[0], t1.b[1]);
printf ( "t2:a=%d, b_0=%d, b_1=%d\n", t2.a, t2.b[0], t2.b[1]);
return 0;
}
t1:a=1, b_0=42, b_1=173> gcc test.c -Wall
> a.out
t2:a=1, b_0=42, b_1=173
It works, but I am a little confortable with this
solution. Would it be better to use a function, which
copy each variable?
t1:a=1, b_0=42, b_1=173> gcc test.c -Wall
> a.out
t2:a=1, b_0=42, b_1=173
Thanks in advance
Michael