1

Passing an array to a function, do it need to use &?

In below example Case 1 or Case 2, which one is good ?

#define IP_ADDR_LEN  4 
char ip[4]={192,168,205,1};
char PeerIP[4];
int main()
{
   memcpy(PeerIP,ip,IP_ADDR_LEN)

   testip(PeerIP);   /* Case 1 */

   testip(&PeerIP);   /*Case 2*/
}

int testip(char *ip)
{
  /* IP check */

}
1
  • Note that you should declare (or define) testip() before you call it. If you do that, the compiler will be able to tell you that the testip(&PeerIP); call is passing the wrong type to the function — it's an int (*)[4] and not an int * that is being passed. Find out how to make your compiler insist on functions being defined or declared before being used, with strict prototypes, and then use it. Commented Jan 19, 2017 at 7:35

1 Answer 1

2

The first one.

  testip(PeerIP);

is the right way to do it, as an array name will decay to a pointer to the first element of the array, which matches the expected type for the called function parameter.

To elaborate, in your code, testip() expects an argument of type char * and by calling it like testip(PeerIP); you are passing a char *, so no issues.

In case you use the &PeerIP, the type will be [char (*) [4]] pointer to array, not pointer to the first element of the array [char *] and they are different type.

Quoting C11, chapter §6.3.2.1, Lvalues, arrays, and function designators, (emphasis mine)

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]

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

3 Comments

Different type, but both point to the same address. Only pointer arithmetic will differ.
@StoryTeller right, but still the later would be wrong. Just because they point to same address doe not mean the expressions are interchangeable. Types matter. :)
They do indeed matter very much. I just had my c++ background pop up. Where casting pointers to array references is done "correctly" thanks to that fact :)

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.