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



我使用的代码有一个错误,想知道是否有人可以帮助调试。看起来我们得到了一个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。CCD_ 3随后将返回指向该存储器块的指针。

以下是一个简短的实现:

#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;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAXSIZE 64
typedef struct word {
    char word[MAXSIZE];
    int freq;
} Word;
int word_counter = 0;
size_t pointer_counter = 16;//Number of pointers that ensure
void readWords(char norm_word[MAXSIZE], Word ** array) {
    int i = 0;
    bool found = false;
    Word *current_pointer = *array;
    for (i=0; i<word_counter; i++) {
        if(strcmp(norm_word, current_pointer->word) == 0){
            found = true;
            current_pointer->freq++;
            break;
        }
        ++current_pointer;
    }
    if(!found) {
        if(pointer_counter == word_counter) {
            pointer_counter *= 2;
            *array = realloc(*array, sizeof(Word)*pointer_counter);
        }
        Word *new_pointer = *array + word_counter;
        new_pointer->freq = 1;
        strcpy(new_pointer->word, norm_word);
        ++word_counter;
    }
}
int main(void){
    Word *vocabulary = calloc(pointer_counter, sizeof(Word));
    char norm_word[MAXSIZE];
    while(1==scanf("%s", norm_word)){
        readWords(norm_word, &vocabulary);
    }
    {
        int i;
        for(i = 0; i < word_counter; ++i){
            printf("%s(%d)n", vocabulary[i].word, vocabulary[i].freq);
        }
    }
    free(vocabulary);
    return 0;
}

相关内容

  • 没有找到相关文章

最新更新