0

I got this warning: incompatible pointer types passing 'char (*)[1024]' to parameter of type 'char *'

My code looks like this:

myfunc(char* sString, size_t s_tString)
{
   memset(sString, '\0', s_tString);
   ...
   fPipe = (FILE *)popen (sString, "r");
   ...
}

int main()
{ 
   ...
   char sString[1024];
   myfunc(&sString, sizeof(sString));
   ...
}

After calling myfunc sString has the value I was expecting but the compiler throws that warning... After asking some coworkers I get why I'm getting that warning but we don't know why the code is still working.

I'm looking for the explanation of why this happens, the fix is pretty simple, rmove the & from the call.

J63
  • 833
  • 1
  • 8
  • 22

2 Answers2

2

If you use sString is will decay to a pointer to its first element, i.e. &sString[0] which is of type char *.

When you use &sString you get a pointer to the array, which is of type char (*)[1024].

Those two pointers are semantically very different, but fortunately for you they both point to the same location so the function you call works as expected.

To solve the warning, drop the address-of operator & in the call, so only do

myfunc(sString, sizeof(string));
//     ^
// Note: No & here
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

It works since the actual value of &sString and sString end up being the same. The types differ, which triggers the warning, but the address the called function sees is still sane, i.e. it can be treated as a character buffer.

This is because there is no run-time memory representing sString itself, so all the compiler can do when you take its address is return the address of the first element.

unwind
  • 391,730
  • 64
  • 469
  • 606