我正在使用的代码有错误,想知道是否有人可以帮助调试。似乎我们遇到了 malloc 错误。谢谢。
void readWords(char norm_word[MAXSIZE], Word ** array) {
int i = 0;
bool found = false;
int result = 0;
Word * current_pointer = malloc (sizeof(Word*));//creates a temporary variable for each pointer in the array
for (i=0; i<word_counter; i++) {
current_pointer = *(array+i); //accesses the current pointer
result = strcmp(norm_word, (current_pointer -> word)); //compares the string to each stored string
if (result == 0) {
found = true;
(current_pointer->freq)++;
break;
}
}
if(!found) {
if(pointer_counter == word_counter) {
array = realloc(array, sizeof(array)*2);
pointer_counter*=2;
}
Word * new_pointer = (Word*) malloc (sizeof(Word*));
strcpy(new_pointer -> word, norm_word);
*(array + (pointer_counter - 1)) = new_pointer;
word_counter++;
}
;
}
最佳答案
系统上所有指针的大小都相同。因此,sizeof
总是为任何指针返回相同的大小。您想要为结构分配空间,因此需要在不带星号的名称上使用 sizeof
。 malloc
随后将返回指向该内存块的指针。
这是一个简短的实现:
#include <iostream>
#include <string>
typedef struct
{
int num;
int numnum;
}numbers;
int main(int argc, char ** argv)
{
numbers* n = (numbers*)malloc(sizeof(numbers));
n->num = 1;
n->numnum = 2;
free(n);
return 0;
}
关于c - 将单词读入结构数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26187739/