Our coding style is we pass a pointer to a struct to a function, when we are modifying the contents of the structure.
However, when we are not modifying the contents of a struct, is there still any reason to prefer passing a pointer to a struct to a function?
Pointers reduce length and complexity of programs. Pointers increase the execution speed and thus reduce the program execution time. Pointers provide an efficient tool for manipulating dynamic data structures such as structure, union, linked list etc.
Using pointer in C programming has following advantages: Pointers provide direct access to memory. Pointers provide a way to return multiple values from a user defined function without using return keyword. Pointers reduce the storage space and complexity of programs.
Pointers can also be passed as an argument to a function like any other argument. Instead of a variable, when we pass a pointer as an argument then the address of that variable is passed instead of the value. So any change made to the pointer by the function is permanently made at the address of the passed variable.
Pass-by-pointer passes the address of some data, a variable, to a pointer parameter. So, one advantage of a pass-by-pointer is that the time needed to perform the pass is independent of the size of the data - passing a large structure by pointer takes no more time than passing a small structure.
The advantage is in the size being passed: when you pass a large struct
, the compiler generates code to make a copy of that struct
if you pass it by value. This wastes CPU cycles, and may create a situation when your program runs out of stack space, especially on hardware with scarce resources, such as embedded microcontrollers.
When you pass a struct
by pointer, and you know that the function must not make modifications to it, declare the pointer const
to enforce this rule:
void take_struct(const struct arg_struct *data) {
data->field = 123; // Triggers an error
}
Yes, the pointer's size is usually much smaller than the entire struct's size. You save stack and time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With