char*var=NULL;和有什么区别?和charvar[LENGTH+1];?
我正在创建一个函数来加载一个哈希表,如果我的代码看起来像这样,我就会遇到分段错误
bool load(const char *dictionary)
{
// initialize vars
char *line = NULL;
size_t len = 0;
unsigned int hashed;
//open file and check it
FILE *fp = fopen(dictionary, "r");
if (fp == NULL)
{
return false;
}
while (fscanf(fp, "%s", line) != EOF)
{
//create node
node *data = malloc(sizeof(node));
//clear memory if things go south
if (data == NULL)
{
fclose(fp);
unload();
return false;
}
//put data in node
//data->word = *line;
strcpy(data->word, line);
hashed = hash(line);
hashed = hashed % N;
data->next = table[hashed];
table[hashed] = data;
dictionary_size++;
}
fclose(fp);
return true;
}
但是如果我更换
char *line = NULL;by char line[LENGTH + 1];(其中长度为 45)
有用。它们不是“等效”的吗?
回答
当你这样做时,fscanf(fp, "%s", line)它会尝试将数据读入指向的内存line- 但char *line = NULL;不分配任何内存。
当你这样做时,char line[LENGTH + 1];你分配了一个LENGTH + 1 chars数组。
请注意,如果文件中的单词比LENGTH您的程序长,则写入越界。始终使用边界检查操作。
例子:
while (fscanf(fp, "%*s", LENGTH, line) != EOF)
THE END
二维码