Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to struct or struct itself?

Consider this code:

struct s { /* ... */ };

void f(struct s x) { /* ... */) /* (1) */
/* or */
void f(const struct s *x) { /* ... */ } /* (2) */

When struct s has a decent size, in which case should we prefer the first form?

like image 587
md5 Avatar asked Oct 16 '12 19:10

md5


2 Answers

Are you asking which is better?

It depends what you are trying to do - the second form with a pointer will be more efficient. But if you just want to pass a value to f and not have to worry about side-effects then you might go with the first signature - as long as the struct is not too large.

like image 147
Justin Ethier Avatar answered Sep 22 '22 02:09

Justin Ethier


I would suggest reading this.

When struct sis of decent size as you say, then you should avoid passing it by value, especially in recursive functions.

Passing a struct by value means that it gets copied before the function invocation. That results in slower execution and greater memory utilization. Also note that the struct is going to be allocating in the stack and in some systems the stack size is pretty limited.

I would suggest using a pointer in every case unless you need multiple copies of a structure to be modified by functions and you don't want those modifications only visible within each function's scope.

like image 45
zakkak Avatar answered Sep 20 '22 02:09

zakkak