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?

More than 1 year has passed since last update.

C言語 char a[20]に値設定できない!!!

Posted at

はじめに

こんにちは。
30代から未経験からエンジニアです。

大変です。
文字型と文字列型が違うことは理解できたのですが、今度は値を設定できなくなってしまいました・・・。

初歩だと思うのですが、備忘録に残します。

なぜ代入できない?

まず今回やりたかったことを説明いたします。

test.c
char a[20];

a = "dainyuusitai";
puts(a);

ん?
左辺値に関するエラーが出ている?

と思い色々やってみました。

test.c
char a[20];

a[0] = "dainyuusitai";
puts(a);

これも例外処理流れて実行できず。

結局よくわからず下記初期化宣言で対応。

test.c
char a[20]= "dainyuusitai";

puts(a);

できたけども・・・

あとから値を受けて入れるときにこれだと不便だと思い調べる。

一応こんな感じでもいけるらしい。

test.c
	char a[20];
	a[0] = 'd';
	a[1] = 'a';
	a[2] = 'i';
	a[3] = 'n';
	a[4] = 'y';
	a[5] = 'u';
	a[6] = 'u';
	a[7] = 's';
	a[8] = 'i';
	a[9] = 't';
	a[10] = 'a';
	a[11] = 'i';
	a[12] = '\0';
	printf("%c", a[0]); // 一番最初の「d」が取れる。

いや、めんどいよ!

てことで解決策書いていきます。

解決策

てことで、調べたらこんなのありました: strcpy(配列変数 , "いれたい文字列");

test.c
#include <string.h> //下記includeが必要です。
#pragma warning(disable : 4996) //非推奨エラー非表示にできる。

	char a[20];
	strcpy(a, "dainyuusitai");
	puts(a); //結果「dainyuusitai」と表示できました。

とこんな感じで解決できるみたいです。

とまあ、他の言語と違いString型がなかったのでこんな最初の方で苦戦しましたので書いておきます。
(自分への戒めです。)

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?