Rajeesh Rarankurissi
Rajeesh Rarankurissi

Reputation: 149

Passing char array to a function

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 */

}

Upvotes: 1

Views: 3266

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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. [...]

Upvotes: 2

Related Questions