我的程序的目标是读取一个文件,并输出出现次数最多的单词以及它的出现次数。但我在使用malloc和它的语法方面遇到了问题。
以下是malloc所指向的结构体:
struct Word_setup {
char word[max_length];
int count;
};
这一部分的主要帮助我发现了我的错误:
printf("Pre-Allocation Test");
struct Word_setup *phrase;
phrase = (struct Word_setup *) malloc(SIZE);
if (phrase == NULL)
{printf("Failure allocating memory"); return 0;}
它似乎只打印出“Pre-Allocation Test”,然后就停止了。就像我之前说的,我不确定如何解决这个问题,但我已经将其隔离出来。
*如果你想知道“SIZE”是什么:
#define SIZE (sizeof(phrase))
编辑:
对于那些好奇编译器版本/操作系统等信息的人:
Windows 7 64位,GCC 4.9.2
如果您需要更多相关信息,请告诉我。
#define SIZE (sizeof(*phrase))
- BLUEPIXYtype
类型,使用type *ptr = malloc( sizeof(*ptr) );
仍然是非常值得的,因为这样可以避免掉入这种错误。 - edmz