c - 将单词读入结构数组的函数

标签 c arrays struct malloc

我正在使用的代码有错误,想知道是否有人可以帮助调试。似乎我们遇到了 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 总是为任何指针返回相同的大小。您想要为结构分配空间,因此需要在不带星号的名称上使用 sizeofmalloc 随后将返回指向该内存块的指针。

这是一个简短的实现:

#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/

相关文章:

javascript - 过滤掉对象数组中没有任何空值的对象

java - 如何在java中声明调用二维数组?

c++ - 从文件中读取数据并存储到结构数组中

c - 与外部 SPI 闪存通信时是否应该禁用中断?

c - 编译器的语义阶段

c - 基于变量 C 对链表进行排序

c - C中标准输出的方向是什么

java - 数组中同一索引有两个值

swift - 如何正确地在 Swift 中的变异结构上创建惰性派生属性?

struct - Elixir:将 sys.config 的结构转换为 erlang