user2131316
user2131316

Reputation: 3277

how to pass struct as parameter and memcpy it in C?

I have the following code:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
   int a[3];
} A;

typedef struct
{
   int b;
} B;

typedef struct
{
    A a;
    B b;
} C;

void getC(C *c_p)
{
    C c;
    c.a.a[0] = 1;
    c.b.b = 1;
    memcpy(c_p, &c, sizeof(C));
}

int main()
{
    C *c;
    getC(c);
}

and it says the process returned, I really can not find the reason, I assume the memcpy part is not working, can anyone helps?

Upvotes: 2

Views: 682

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

The error is in your main, where you pass an uninitialized pointer to getC. You should make it point to something, like this:

C c;
getC(&c);

or

C *c = malloc(sizeof(C));
getC(c);
...
free(c);

Moreover, you do not need to use memcpy with structs - an assignment will work as well:

void getC(C *c_p)
{
    C c;
    c.a.a[0] = 1;
    c.b.b = 1;
    *c_p = c; // No memcpy
}

Upvotes: 4

Related Questions