Copying arrays of structs in C

后端 未结 6 958
后悔当初
后悔当初 2021-02-06 12:03

It\'s been a long since I don\'t use C language, and this is driving me crazy. I have an array of structs, and I need to create a function which will copy one array to another (

6条回答
  •  无人及你
    2021-02-06 12:34

    In my case previous solutions did not work properly! For example, @Johannes Weiß's solution did not copy "enough" data (it copied about half of the first element).
    So in case, somebody needs a solution, that will give you correct results, here it is:

    int i, n = 50;
    struct YourStruct *a, *b;
    
    a = calloc(n, sizeof(*a));
    b = malloc(n * sizeof(*b));
    for (i = 0; i < n; ++i) { 
        // filling a
    }
    
    memcpy(b, a, n * sizeof(*a)); // <----- see memcpy here
    
    if (a != NULL) free(a);
    a = calloc(n*2, sizeof(*a));
    
    memcpy(a, b, n * sizeof(*b)); // <------ see memcpy here again
    

    Some notes, I used calloc for a, because in the '// filling a' part I was doing operations that required initialized data.

提交回复
热议问题