4

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?

5
  • 4
    By using struct test_object s[] as argument, the compiler actually sees it as struct test_object *s. So you're already passing a pointer (to the first element). Commented Aug 10, 2017 at 9:10
  • 1
    Passing an array as an argument technically equals passing a pointer to its first element, so if you passed a pointer to an array, you would've simply passed a pointer to a struct pointer, which might be sometimes useful but unnecessary here Commented Aug 10, 2017 at 9:11
  • Use C99+ and a vla argument. Commented Aug 10, 2017 at 9:11
  • @artic sol Unclear what you're asking. Commented Aug 10, 2017 at 9:14
  • @AnttiHaapala Beware that VLAs are optionals in C11 Commented Aug 10, 2017 at 9:16

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.