0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C言語】puts関数の使い方間違えた

0
Last updated at Posted at 2025-10-16

はじめに

こんにちは、Juna1013です。
先週末に応用情報技術者試験を受けてきました。
結果はクリスマスに分かるので楽しみです。

さて、今回はC言語の実装にてputs関数の使い方を間違えたため、備忘録としてまとめていこうと思います。

puts関数とは?

一言でまとめれば、printf()に標準で改行\nを付け加えた関数です。

何やらかしたの?

アルゴリズムの授業にてポインタ変数をインクリメントする例題が出題され、以下のように実装しました。

#include <stdio.h>
int main(void) {
    int scores[] = {10, 20, 30};
    int *p = scores;
    
    puts(*p); 
    p++; 
    puts(*p);
    p++;
    puts(*p);
    
    return 0; }

コンパイルしようとしたところ、以下のようなエラーが出力されました。

sample08.c:8:10: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Wint-conversion] 8 | puts(*p); | ^~ 
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/_stdio.h:267:23: note: passing argument to parameter here 267 | int puts(const char *); | ^ sample08.c:10:10: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Wint-conversion] 10 | puts(*p); | ^~ 
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/_stdio.h:267:23: note: passing argument to parameter here 267 | int puts(const char *); | ^ sample08.c:12:10: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Wint-conversion] 12 | puts(*p); | ^~ 
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/_stdio.h:267:23: note: passing argument to parameter here 267 | int puts(const char *); | ^ 3 errors generated.

エラーメッセージによるとputs()を使用した行でエラーが発生しているようです。
チャッピーに対処法を確認したところ、

  • puts()は文字列を出力する関数である
  • しかし*pは 整数(int)である(scores配列の要素だから)

との返答がありました。要は型エラーですね。
対処法としては、おとなしくprintf()を使えとのことでした。

#include <stdio.h>

int main(void) {
    int scores[] = {10, 20, 30};
    int *p = scores;

    printf("%d\n", *p);
    p++;
    printf("%d\n", *p);
    p++;
    printf("%d\n", *p);

    return 0;
}

おわりに

型エラーってPythonやJavaScriptなど動的型付けの言語でしか起こり得ないと思っていたのでいい経験になりました。
文法ちゃんと勉強します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?