前提・実現したいこと
テキストファイルを読み込み、構造体のポインタ配列に代入し、表示させるプログラムを作ろうと思っています。
発生している問題
構造体を1つにしたところ上手くできたのですが、構造体を2つにするとなぜ全ての要素に同じものが代入されてしまうのかがわからず困っています。
できれば解決方法も教えていただきたいです。
該当のソースコード
C
1#include <stdio.h> 2#include <stdlib.h> 3#include <string.h> 4 5typedef struct species{ 6 char name[20]; 7 int hp; 8 int atk; 9 int def; 10}species; 11 12typedef struct character{ 13 struct species *spe; 14 int lv; 15 }character; 16 17int main(void){ 18 FILE *file; 19 int counter=0,currentSize=10; 20 int i; 21 character *chara; 22 char str[40],name[20]; 23 chara=(character *)malloc(currentSize*sizeof(character)); 24 file=fopen("test.txt","r"); 25 while(fgets(str,40,file)!=NULL){ 26 character temp; 27 species temp2; 28 sscanf(str,"%s %d %d %d\n", 29 temp2.name,&temp2.hp, 30 &temp2.atk,&temp2.def); 31 temp.lv=1; 32 temp.spe=&temp2; 33 chara[counter]=temp; 34 chara[counter].lv=1; 35 counter++; 36 for(i=0;i<counter;i++){ 37 printf("%s %d %d %d %d\n", 38 chara[i].spe->name,chara[i].spe->hp, 39 chara[i].spe->atk,chara[i].spe->def,i); 40 } 41 } 42 free(chara); 43 fclose(file); 44} 45
###読み込んだテキストファイル
AAA 1 2 3 BBB 4 5 6 CCC 7 8 9
実行結果
AAA 1 2 3 0 BBB 4 5 6 0 BBB 4 5 6 1 CCC 7 8 9 0 CCC 7 8 9 1 CCC 7 8 9 2
実現したい実行結果
AAA 1 2 3 0 AAA 1 2 3 0 BBB 4 5 6 1 AAA 1 2 3 0 BBB 4 5 6 1 CCC 7 8 9 2
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/09 14:55
2018/12/09 23:38
2018/12/11 11:22