So, here we are talking about STRUCTURES & FUNCTIONS.
Basically there are three methods by which invoker and invoked structure function can communicate to each other.
- Passing each member of the structure as an actual argument of the function call, or returning to the each member type.
- Sending the copy of the structure to the entire called function or returning to the struct type (call by value).
- Using pointers, pass the structure as an argument and indirectly work on the original structure or returning the address of the struct (call by reference).
Your, CASE 1:
Array create_array_type_one(int size) {
Array result;
result.length = 0;
result.elements = (int *)malloc(size * sizeof(int));
return result;
}
In this case you are returning a copy of the entire structure to the calling function. So, in order to use it in your main() function, you should do something like this:
Array new;
new = create_array_type_one(5);
Here, you are assigning the returned structure of type Array to a structure of type Array.
In CASE 2:
Array* create_array_type_two(int size) {
Array *array = (Array *) malloc(sizeof(Array));
array->length = 0;
array->elements = (int *) malloc(sizeof(int) * size);
return array;
}
In this case you are using pointers and returning a pointer to the newly created data structure of type Array. You are not sending a copy of the structure to the calling function instead you are sending its address to the calling function. Therefore, what happening in the main() while calling like this is:
Array *ptr;
ptr = create_array_type_two(5);
Both cases has there own advantages and disadvantages like CASE 1 ensures data safety as all the work done by the called function happens on a copy but uses extra memory. Where CASE 2 is more efficient and faster as compared to the previous method, as it uses same memory location for the operation.