コンパイラは文字列定数(二重引用符で囲った文字列)を見つけると、それを文字列テーブルに格納し、その文字列定数へのポインタを生成する。なので、ポインタに直接文字列定数を代入することができる(実際には文字列定数を指すポインタが代入される)。
#include
int main(void)
{
char *p;
p = "One Two Three\n";
printf(p);
return 0;
}
takatoh@nightschool $ gcc sample_6_4.c -o sample_6_4
sample_6_4.c: In function ‘main’:
sample_6_4.c:10:5: warning: format not a string literal and no format arguments [-Wformat-security]
printf(p);
^
takatoh@nightschool $ ./sample_6_4
One Two Three
なんか warning が出てるな。結果はちゃんと期待どおりのものが出力されてるけど。
フォーマットが文字列リテラルじゃなくて引数がないってこと?
次のように直したら warning がでなくなった。
#include
int main(void)
{
char *p;
p = "One Two Three\n";
printf("%s", p);
return 0;
}
takatoh@nightschool $ gcc sample_6_4a.c -o sample_6_4a takatoh@nightschool $ ./sample_6_4a One Two Three