プロが教えるわが家の防犯対策術!

構造体の各データの表示について以下のようなプログラムを作成しました。

#include <stdio.h>

struct tb{
char name[20];
char sex;
int age;
double height;
double weight;
};

int main(void)
{
int i;

struct tb test[2];

test[0].name="amada"
test[0].sex='f';
test[0].age=20;
test[0].height=172.5;
test[0].weight=62.5;

test[1].name="okada";
test[1].sex='f';
test[1].age=21;
test[1].height=180.2;
test[1].weight=70.8;

for(i=0; i<2; i++){
printf("%s %s %d %f %f \n",test[i].name,test[i].sex,test[i].age,test[i].height,test[i].weight);
}

return 0;
}

ファイル名を適当にsample.cとしてgcc sample.c した所、以下のようなコンパイルエラーが出ました。

sample.c: In function ‘main’:
sample.c:18: error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’
sample.c:18: error: expected ‘;’ before ‘test’
sample.c:23: error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’

このエラーを元にソースをどのように修正したらよいか教えて頂けますでしょうか?
よろしくお願いいたします。

A 回答 (4件)

test[0].name="amada"


これを
strcpy(test[0].name,"amada");

test[1].name="okada";
これも
strcpy(test[1].name,"okada");

です。
間違いの理由は
文字列へ文字列へのポインターを代入したとエラーになっています。
つまり、
test[1].name="okada";
これは暗示キャストをつけると
(char[20])test[1].name=(char *)"okada";
なので、型が違うので代入はできないよーということです。

この回答への補足

ありがとうございました。おかげ様で解決できました。

補足日時:2010/05/19 23:49
    • good
    • 1

エラーメッセージに書いてある通り


構造体を以下のように定義するか
struct tb{
char name[20]; -> char *name
char sex;
int age;
double height;
double weight;
};

#include <string.h>
を追加して
strcpy(test[0].name,"amada");
にするかのいずれか(後者の方がいいと思うけどね)

あとは
>test[0].name="amada"
文末に;が無いね。

この回答への補足

直してもエラーが出たので詰まりましたが、アドバイスのおかげで
何とか出来ました。ありがとうございました

補足日時:2010/05/19 23:51
    • good
    • 0

sample.c:18: error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’



構造体の宣言時の初期設定以外で、配列要素に文字列リテラルは代入できません。
strcpy関数等でコピーしてください。


sample.c:18: error: expected ‘;’ before ‘test’

文末の「;」が抜けています。

sample.c:23: error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’

これが一番上と同じ。

この回答への補足

「;」にすら気付かないとは… 焦っていたのかな?
ありがとうございました。

補足日時:2010/05/19 23:52
    • good
    • 0

まずtest[0].name="amada"に『;』が抜けています。

まあ今回はこれが原因ではありませんが・・・・

最初に#include <stdio.h>だけなく#include <string.h>をその下に入力してください。

次にtest[0].name="amada";では実行できません。
strcpy(test[0].name,"amada");と書き換えてください。

同様にtest[1].name="okada";をstrcpy(test[1].name,"okada");に書き換えてください。

これでいいはずですよ

この回答への補足

文字のコピーはそのままではダメなんですね。
勉強になりました。ありがとうございました。

補足日時:2010/05/19 23:53
    • good
    • 1

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!