下面的两个struct字段定义如何彼此区分。
//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
...
最佳答案
2个struct
定义之间的区别是,您要在一个struct
中预分配存储,并在另一个struct
中声明一个指针。
在您的第一个struct
中,您有char *
。 char *
是一个指针。它没有指向任何东西。您需要动态分配一些内存,然后将char *
指针指向该分配的内存。
在第二个struct
中,您有char name[4]
。这是一个数组,您将为此数组分配4个字节。这已分配并准备使用。
如果您事先不知道缓冲区的大小,请使用第一个struct
。使用malloc
分配任意数量的内存,例如1024字节。然后一次读入1024字节的数据。继续执行此操作,直到可以计算出总数据量,然后使用malloc
分配该内存量,然后读入数据。
如果您知道数据始终为4个字节,并且永远不会大于或小于该字节,请使用第二个struct
。如果需要,可以这样声明:char name[500]
。这将为您预分配500个字节,并且只要您的字符串不超过499个字符,此命令就可以使用。但是,您可能会浪费内存(如今这没什么大不了的)。解决此问题的最有效方法是使用malloc
动态分配您实际需要的内存量
最后一个警告...。请记住,C语言中的字符串需要足够的内存来存储字符串本身,外加空终止符。例如:
/* I am allocating 5 bytes to store my name.
My name is Alan, so I'm allocating 4 bytes
plus 1 additional byte for the null terminator
*/
char myName[5];
myName[0] = 'A'; // A
myName[1] = 'l'; // l
myName[2] = 'a'; // a
myName[3] = 'n'; // n
myName[4] = '\0'; // Null Terminator
printf("%s", myName); // Prints Alan