A flexible array element that is not copied when I make a shallow copy of the structure

I made a shallow copy of the structure, which I have as follows:

struct Student{
        char *name;
        int age;
        Courses *list;  //First course (node)
        Student *friends[];   //Flexible array member stores other student pointers
    }Student;

void shallowCopy(const Student *one){
    Student *oneCopy = malloc(sizeof(one) + 20*sizeof(Student*));

    *oneCopy = *one;     <--------------- ERROR POINTS TO THIS LINE
}

When I check the first element of a flexible element of an array oneCopy, it is zero. But if I check the first element of the flexible element of the array in the original structure, it will successfully print the pointer. All other components of the original structure are copied as a name and a linked list. Only the flexible member of the array is not copied. Does anyone know what I'm doing wrong?

+1
source share
2 answers

Does anyone know what I'm doing wrong?

Trying to use assignment to copy a structure using a flexible array element. From the standard (6.7.2.1):

*s1 = *s2 n [.. , ]; - sizeof (struct s) , .

, C , , , , , , , :

, , , , , .

, sizeof(*one) , , , *oneCopy = *one;.

, , , malloc memcpy. , - ( , ), , one->friends
oneCopy->friends.

+3

. , .

typedef struct Student
^^^^^^^
{
    char *name;
    int age;
    Courses *list;  //First course (node)
    struct Student *friends[];   //Flexible array memeber stores other student pointers
    ^^^^^^^^^^^^^^
} Student;

malloc

Student *oneCopy = malloc(sizeof(one) + 20*sizeof(Student*));

Student *oneCopy = malloc(sizeof( *one ) + 20*sizeof(Student*));
                                  ^^^^^

, ,

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

typedef struct Student
{
    char *name;
    int age;
//    Courses *list;  //First course (node)
    struct Student *friends[];   //Flexible array memeber stores other student pointers
} Student;

Student * shallowCopy( const Student *one, size_t friends )
{
    Student *oneCopy = malloc( sizeof( Student ) + friends * sizeof( Student * ) );

    *oneCopy = *one;

    memcpy( oneCopy->friends, one->friends, friends * sizeof( Student * ) );

    return oneCopy;
}

int main( void )
{
    Student *one = malloc( sizeof( Student ) + sizeof( Student * ) );

    one->friends[0] = malloc( sizeof( Student ) );

    one->friends[0]->age = 20;

    Student *oneCopy = shallowCopy( one, 1 );

    printf( "Age = %d\n", oneCopy->friends[0]->age );

    free( one->friends[0] );
    free( one );
    free( oneCopy );
}    

Age = 20

, , , .:)

0

Source: https://habr.com/ru/post/1687693/


All Articles