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?

char型とint型

Posted at

文字列を入れる変数を宣言しようとしたときにchar str;って打ってしまい、エラーを吐かれ、色々調べました。

  • 文字もACKIIコードで実態は数値
  • char cは単一文字を格納する変数
  • 文字列を格納したいならchar c[6],char c[] = "abcde"などの配列にする
  • 配列のサイズ、確保するメモリのことを考える必要があるので、ただchar c[]と宣言するのはダメ
  • char型の指定子は%c(単一文字)%s(文字列)
  • 単一文字ならint型として取り扱える。文字列もc[1]のように配列番号を指定してやればint型で取り扱い可能
  • 文字列を%sで渡された関数は、配列を「先頭からヌル文字\0まで」読み込んで処理を行う

自分でごく簡単なコードを書いて確かめてみました。

char型
#include <stdio.h>
#include <limits.h>

int main()
{
  int n;
  printf("整数nを入力 : "); scanf("%d", &n);
  printf("%dはint型では\"%d\"で、char型では\"%c\"\n", n, n, n);
  printf("char型の最小値は%d、最大値は%d\n",CHAR_MIN,CHAR_MAX);
  printf("int型の最小値は%d、最大値は%d\n",INT_MIN,INT_MAX);

  return 0;
}
実行結果
整数nを入力 : -50
-50はint型では"-50"で、char型では"ホ"
char型の最小値は-128、最大値は127
int型の最小値は-2147483648、最大値は2147483647

なるほど。
ちなみに、ASCIIコードの127はDELとのこと。何も表示されないなと思ったら制御文字でした。
本読んで分かっても、いざコード打とうとすると「なんだっけ?」となることが多いです。

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?