I've recently discovered the syntax for pointers to fixed arrays. While experimenting with it, I was surprised to see that pointer decay didn't seem to work as in the below example:
#include <iostream>
int main( int argc, char* argv[] )
{
char pa[3];
//char (*parr)[3] = &pa; // This works.
char (*parr)[3] = pa; // This doesn't work - why?
std::cout << (void*)pa << std::endl;
std::cout << (void*)parr << std::endl;
return 0;
}
Output:
prog.cpp: In function 'int main(int, char**)':
prog.cpp:10:21: error: cannot convert 'char*' to 'char (*)[3]' in initialization
char (*parr)[3] = pa;
^
Compilation performed with gcc-4.9.2 (Code Chef).
Can someone please help identify what is wrong here?
Update:
This is an interesting but even more puzzling finding: the pointer decay works as expected if compiling C-style (I selected "C" as the compiler in Code Chef, although it still shows gcc-4.9.2. Perhaps there are different compiler flags being passed to differentiate between C and C++ compilation.)
The C version of the above code:
#include <stdio.h>
int main( int argc, char* argv[] )
{
char pa[3];
/* char (*parr)[3] = &pa; */
char (*parr)[3] = pa;
printf( "0x%x\n", pa);
printf( "0x%x\n", parr);
return 0;
}
Output from the compiled C code:
0xbf92b1fd
0xbf92b1fd
std::arrayandstd::vector?std::arrayinstead.