Search code examples
cstructconstantsshallow-copy

Is there a way to make a shallow copy of a constant struct to a non-constant struct?


I want to make a shallow copy on an entire struct which has the constant deceleration. But I want the struct that I am copying too to be non constant.

This is what I have done so far which is producing an error:

struct Student{
    char *name;
    int age;
    Courses *list;  //First course (node)
}Student;

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

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

The compiler error I am getting:

Assignment discards 'const' qualifier from pointer target type.

I know I can remove the const from one or add the const to oneCopy, but I want to know if there is a way to make a shallow copy in this specific situation where Student one is a const and the copy Student oneCopy is not.


Solution

  • It should be:

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

    Because you want to assign the struct, not the pointer.