【发布时间】:2017-01-20 05:26:40
【问题描述】:
下面的两个结构字段定义如何相互区分。
//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
正如你使用第二个结构所看到的,它会在字符串之后打印一些垃圾字符。这是为什么呢?
输入字符串:
MSFT 400
YHOO 100
...
【问题讨论】:
-
char name[4];-->char name[5];或更多。另外您需要在使用前分配s1.name。