下の2つの構造体フィールド定義が互いにどのように区別されるか。fscanf/sscanf文字列を構造体フィールドに渡すchar [4]
//first struct
typedef struct{
char *name; //here is the difference
int shares;
} STOCK1;
//second struct
typedef struct{
char name[4]; //here is the difference
int shares;
} STOCK2;
//here inside main()
FILE *fpRead = openFile(input_filename, "r");
STOCK1 s1;
fscanf(fpRead, "%s %d", s1.name, &s1.shares);
printf("%s %d ", s1.name, s1.shares);
STOCK2 s2;
fscanf(fpRead, "%s %d", s2.name, &s2.shares);
printf("%s %d ", s2.name, s2.shares);
コードが印刷されます:
MSFT 400
MSFT� 400
2番目の構造体を使用して見ることができるように、それは文字列の後、いくつかのガベージ文字を印刷します。何故ですか?
入力文字列:
MSFT 400
YHOO 100
...
STOCK2.name
'char name [4];' - > 'char name [5];'以上です。また、使用前に 's1.name'に割り当てる必要があります。 – BLUEPIXY