Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pass array of structs by reference or by value to a function

I have a function in C which takes an array of structs as an argument:

int load_ini_parms(char * ini_file,
                   struct test_object s[],
                   int num,
                   struct lwm2m_object * l)

My question is, would it be better programming practice to pass a pointer to an array of structs? What would be the advantages or disadvantages?

like image 809
artic sol Avatar asked Dec 24 '22 15:12

artic sol


2 Answers

It doesn't make any difference because passing an array as a function argument decays into a pointer.

The function

int load_ini_parms(char *ini_file, struct test_object s[], int num, struct lwm2m_object *l)

is equivalent to

int load_ini_parms(char *ini_file, struct test_object *s, int num, struct lwm2m_object *l)

The information regarding to the size of the array is lost in both cases.

like image 56
ネロク・ゴ Avatar answered Jan 30 '23 11:01

ネロク・ゴ


Contrary to what others here say, I say it does make a difference as to what may be a "better programming practice":

Declaring the parameter as an array indicates to the user of the function that you expect, well, an array.

If you only declare a pointer this does not tell anyone if you expect a single element or possibly multiple.

Hence, I'd prefer the pointer for single-element parameters (e.g. "output" parameters) and the array for (potentially) multiple elements.

like image 40
JimmyB Avatar answered Jan 30 '23 12:01

JimmyB