format '%d' expects argument of type の原因と直し方|printf・scanf の型の対応表【C言語】
C言語
gcc
エラー
警告の読み方
f1.c:9:14: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]日本語にすると「 %d は int が来るはずなのに、2番目の引数(書式の文字列の次)は double だった」です。
argument 1 は "…" の書式文字列。argument 2 がその次の変数
直すのは、書式か変数の型のどちらか、意図に合う方です。
printf の対応表
| 変数の型(警告に出る名前) | printf の書式 | 例 |
|---|---|---|
int | %d | printf("%d", score); |
long int | %ld | printf("%ld", big); |
long long int | %lld | |
unsigned int | %u | |
long unsigned int(sizeof・strlen の結果) | %zu | printf("%zu", sizeof(int)); |
double(float も printf では double になる) | %f | printf("%f", avg); |
char(1文字) | %c | |
char *(文字列) | %s | printf("%s", name); |
| ポインタ(住所) | %p | printf("%p", (void *)p); |
scanf の対応表(printf と違うところに注意)
scanf は「ここに書いて」と住所を受け取るので、警告の型にも * が付きます。
| 読みたい変数 | scanf の書式 | 書き方 |
|---|---|---|
int n | %d | scanf("%d", &n); |
long n | %ld | scanf("%ld", &n); |
double x | %lf(printf の %f と違う) | scanf("%lf", &x); |
float x | %f | scanf("%f", &x); |
char buf[16] | %s | scanf("%15s", buf);(& は付けない) |
gcc 13 で、scanf の書き間違いを3つ並べたときの警告です。
f2.c:7:13: warning: format '%f' expects argument of type 'float *', but argument 2 has type 'double *' [-Wformat=]
f2.c:8:13: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
f2.c:9:13: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[16]' [-Wformat=]1つ目:double を %f で読もうとした → %lf に
2つ目: & を忘れた(int * が欲しいのに int)→ &n に。これはmakes pointer from integer の記事と同じ原因です
3つ目:配列に & を付けた → buf だけに
間違えたまま実行するとどうなるか
警告を無視して実行してみました(gcc 13・x86-64 の Linux)。
double avg = 72.5;
long big = 3000000000L;
printf("%d\n", avg);
printf("%d\n", big);
printf("%f\n", 80);-1268297272
-1294967296
72.5000001行目:72.5 ではなく、でたらめな数
2行目:30億が int に入りきらず、マイナスの数
3行目:80 を %f で出したのに、前の行の 72.5 が出た
3行目がいちばん不思議ですが、x86-64 では double と int が別の場所(小数用のレジスタと整数用のレジスタ)で関数に渡されます。 %f は小数用の場所を見に行くので、そこに残っていた 72.5 を表示してしまいました。結果は環境によって変わり、正しい値が出ることもあるので気づきにくいのがこの警告の怖いところです。
scanf("%f", &x) (x は double)も、3.14 を入力して 0.000000 が表示されました。値が読めていないのに、エラーにはなりません。
型ごとのデータの大きさ(int は4バイト、double は8バイトなど)は、C言語入門の型と計算で図にしています。
警告を必ず見る設定
-Wall を付けると、書式の間違いを全部教えてくれます。
$ gcc -Wall main.c授業の課題などでは、最初から -Wall を付けてコンパイルし、警告が0件になるまで直すのがおすすめです。
まとめ
format '%d' expects argument of type は、書式と変数の型が合っていない警告
警告の has type '〇〇' を見て、対応表で書式を選ぶ(double は printf %f ・scanf %lf 、sizeof は %zu )
実行はできても、表示はでたらめ。 -Wall で警告を0件にする
ほかのエラーは、stray '\343' in program、undefined reference to、makes pointer from integer without a cast、implicit declaration of function でまとめています。
C言語でよく出るエラーはC言語 エラー一覧にまとめています。