cvariablesmemorystructvariable-declaration

C - Struct variable inside callee function, should it be a pointer or dosent it matter


im kinda confused how memory allocation for struct variables works and how the struct variables declaration works.

My understanding is, that when im declaring a struct variable outside of a function, (and use it, so it doesnt get optimized by the compiler), the memory gets reserved for the total size of the struct (and maybe more for padding).

Im confused about what happends inside functions/ when the structure isnt initilized but passed on from somewhere else.

Example code:

typedef struct mystruct MyStruct;
typedef struct myinnerstruct MyInnerStruct;

struct myinnerstruct{
    int b;
};

struct mystruct{
    int a;
    MyInnerStruct some;
};

.....

void someFunc(MyStruct* some_ptr){

    MyInnerStruct something = some_ptr->some;
    // Or
    MyInnerStruct* something = &some_ptr->some;

}

In the Example, someFunc has the parameter some_ptr with the type pointer of MyStruct. Because if MyStruct itself would be used, the parameter would have as much memory as MyStruct needs, not only memory for the starting address of the struct.

But what about the Variables inside the function? Are both expressions equal or what would happen here. Like it wont copy the myinnerstruct, so could it even use more memory?

edit: in this case i mean the MyInnerStruct Variable shouldnt be copied, it should only be used to access the corresponig elements of the passed original struct.

Furthermore the code is ment as an example, the mystruct, myinnerstruct etc. can be much more complex, holding many variables, pointers and also other structures


Solution

  • edit: in this case i mean the MyInnerStruct Variable shouldnt be copied, it should only be used to access the corresponig elements of the passed original struct.

    Then the function is poorly designed, it should use const correctness:

    void someFunc(const MyStruct* some_ptr){
    

    After which we can conclude that we would need to access the inner struct to a similar pointer to read-only memory:

    const MyInnerStruct* something = &some_ptr->some;
    

    This doesn't copy anything. However, there is no obvious need to create this extra pointer variable, we could just access some_ptr->some directly.

    Whereas MyInnerStruct something = some_ptr->some; would make a "hard copy" of the inner struct - an identical copy allocated locally. Modifying the local copy wouldn't affect the struct on the caller side either. It is fine to copy structs like this, as long as they don't contain any pointer members pointing at memory allocated elsewhere. But copying just for the heck of it is a bad idea since copying takes up execution speed.