Why is the code below working? Should that be a compilation error (or at least a run-time error)?
#include <stdio.h>
int main(int argc, char** argv){
float *buf = "happy holiday"; // notice the float
printf("content of buf = %s\n",buf); //its working
return 0;
}
I compiled it and got just a warning:
~/Desktop/cTest>gcc -o run run.c
run.c: In function `main':
run.c:4: warning: initialization from incompatible pointer type
You should always compile with
-Wall -Werror -Wextra(at a minimum). Then you get this:It “works” because in practice, there’s no difference between a
char *and afloat *under the hood on your platform. Your code is really no different to:This is well-defined behaviour, unless the alignment requirements of
floatandchardiffer, in which case it results in undefined behaviour (see C99, 6.3.2.3 p7).