Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

advantage of passing pointer to a struct as argument?

Tags:

c

pointers

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?

like image 904
Deepak Avatar asked Feb 27 '14 19:02

Deepak


People also ask

What is advantage of pointer in structure?

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.

What is advantage of using pointer to structure C?

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.

Why it is sometimes desirable to pass a pointer as an argument to a function?

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.

What is an advantage of passing pointers to functions instead of variables?

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.


2 Answers

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
}
like image 50
Sergey Kalinichenko Avatar answered Sep 27 '22 00:09

Sergey Kalinichenko


Yes, the pointer's size is usually much smaller than the entire struct's size. You save stack and time.

like image 23
SzG Avatar answered Sep 25 '22 00:09

SzG