Why can I assign a string to a pointer to float?
题
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:
cc1: warnings being treated as errors
test.c: In function 'main':
test.c:4: warning: initialization from incompatible pointer type
test.c:5: warning: format '%s' expects type 'char *', but argument 2 has type 'float *'
test.c: At top level:
test.c:3: warning: unused parameter 'argc'
test.c:3: warning: unused parameter 'argv'
It "works" because in practice, there's no difference between a char *
and a float *
under the hood on your platform. Your code is really no different to:
#include <stdio.h>
int main(int argc, char** argv){
float *buf = (float *)"happy holiday";
printf("content of buf = %s\n",(char *)buf);
return 0;
}
This is well-defined behaviour, unless the alignment requirements of float
and char
differ, in which case it results in undefined behaviour (see C99, 6.3.2.3 p7).
其他提示
This program is not strictly conforming, a compiler is required to output a diagnostic and has the right to refuse to compile it. So don't do it.
This is an unfortunate behavior of gcc
, and if somebody could get it fixed, we'd all be dealing with a lot less buggy software. Unfortunately there's a lack of will to fix many things like this. Submitting a bug report would not hurt.