If a structure in the C language has to be initialized through both memory allocation and default field setting, and if these tasks are to be conveniently accomplished inside a function, then describe how the indicated function has to be coded, which input arguments it may accept, and how it may be called in practice.
When we declare a variable, whether it is a struct or integer there will be memory allocated on the stack. So if i declare an Integer, then there will be memory allocated for that in compile time on the stack. But If i want to allocate memory during runtime, i will do that using dynamic memory allocation and through malloc or calloc depending on the requirements.
Now onto the answer.
In modern C(C99 or Above), if we want to declare and initialize a struct, we can do so using initializer list. In previous versions, we would need to initialize each and every field individually. Also, to allocate memory, we would need to use malloc and pass the size of the struct as a parameter.
So, to make a function that would initialize a struct , we would need a function with a return type of void as we will pass a reference of the struct and modify that reference. So, as parameters, we require a require a reference to the struct(object) and the default values of that struct. If we wish to,we can decide not to pass the parameters and use literals instead.
Fristly,The function would allocate the memory using malloc(the callee of this function doesn't allocate memory) and pass size of the struct as parameter. Depending on the version of C, we might need to typecast the value returned by malloc.
Then we can go ahead and initialize each field of the struct to the ones passed in the parameters.
Since, we modified the reference, we don't need to return anything.
In practice, we can call this function simply by passing a reference of the uninitialized struct and fields as other parameters.
Also, don't create pointers for the struct as it will create a uninitialized pointer and it points to memory we don't want to write to so we can't write safely on it. Simple declare a struct variable and pass it as reference.
//DON'T DO THIS
Struct *obj;
//DO THIS
Struct obj;
initStruct(&obj, "OBJ", 4);
Comments
Leave a comment