排列在结构中并填充他 [英] array in a struct and populate him
问题描述
目前,我有一个研究项目,而我和一个朋友真的不知道如何部分解决问题.
at the moment i have a project for the studies and me and a friend don't really know on how resolve the problem on a part of this.
所以,这是一个C项目.我有2个结构:
So, it's a C project. I have 2 struct :
struct Lib {
char letter;
int capacity;
int size;
char** words[200000];
};
typedef struct Lib Library;
struct Program {
char* loadedFileName[50];
FILE* f;
Library* dictionary;
int totalwords;
};
typedef struct Program Program;
此功能:
void fillDicoFromFile(Program* startup){
rewind(startup->f);
while(!feof(startup->f) && !ferror(startup->f)){
char* word = malloc(sizeof(char) * 30);
fscanf(startup->f, "%s", word);
int indexLib = word[0] - 97;
int sizeLib = startup->dictionary[indexLib].size;
startup->dictionary[indexLib].words[sizeLib] = (char*)malloc(sizeof(char) * (strlen(word)+1));
startup->dictionary[indexLib].words[sizeLib] = word;
startup->dictionary[indexLib].size++;
free(word);
}
CountTotalWords(startup);
}
startup-> dictionary是一个由26个Library组成的数组,当我从文件中得到一个单词时,我检查他的第一个字母并选择好的Library(startup-> dictionary [0]表示'a'...)然后将该单词放在该结构的数组单词"上,但是当我想要printf一些单词时,它就是错误的字符串或错误的字符串.我很确定我们在指针上做错了,但是在哪里...
startup->dictionary is a array of 26 Library, and when i get a word from the file, i check his first letter and select the good Library (startup->dictionary[0] for 'a' ...) and then put the word on the array "word" of the struct, but when i want printf some words, it's bugged strings or wrongs one. I'm pretty sure we're doing wrong on pointers but where ...
我们在做什么错了?
推荐答案
此:
startup->dictionary[indexLib].words[sizeLib] = (char*)malloc(sizeof(char) * (strlen(word)+1));
startup->dictionary[indexLib].words[sizeLib] = word;
...没有按照您的想法做.您正在分配空间(使用malloc
,第一行),但是没有使用它.而是在word
(第二行)中存储指向先前分配的空间的指针.需要明确的是,语句startup->dictionary[indexLib].words[sizeLib] = word
不会复制字符串;它会复制字符串.它只是分配一个指针.
... doesn't do what you think it does. You are allocating space (using malloc
, the first line), but you are not using it; instead, you are storing a pointer to the previously allocated space in word
(the second line). To be clear, the statement startup->dictionary[indexLib].words[sizeLib] = word
will not copy a string; it is just assigning a pointer.
然后,您释放该空间:
free(word);
词典现在包含一个悬挂指针-指向不再分配的区域的指针.解决方法很简单:
The dictionary now contains a dangling pointer - a pointer to an area that is no longer allocated. The fix is easy:
- 删除上面的第一行(使用
malloc
);您不需要为已经分配了空间的单词分配空间 - 删除
free(word)
行;您不希望取消分配此空间,因为它是由字典结构引用的.
- Remove the first line above (which uses
malloc
); you don't need to allocate space for a word that you've already allocated space for - Remove the
free(word)
line; you don't want to deallocate this space, since it is being referred to by the dictionary structure.
这篇关于排列在结构中并填充他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!