C中使用指针

时间:2017-11-05 23:45:06

标签: c

我是C的新手。我玩动态数组字符串。我想将textfile中的所有单词加载到字符串数组中。我动态地将项添加到数组中。它几乎可以工作,但是当我想要打印出来时,我重复了一遍。我认为问题出在dictionary = (char **)realloc(dictionary, sizeof(char *) * (idx));数组应该增加1,原始数据被复制。

int main() {

    FILE *fr;
    int i = 0;
    int c;
    const char *path = "..../sample.txt";
    char *word;
    char **dictionary;
    word = (char *)malloc(sizeof(char));
    dictionary = (char **)malloc(sizeof(char *));

    int idx = 0;    // index of word
    int widx = 0;   // index of char in word

    fr = fopen(path, "r");
    while((c = getc(fr)) != EOF){
        if( c == ' '){
            widx++;
            word = (char *)realloc(word, sizeof(char) * (widx));
            *(word + widx-1) = '\0';
            idx++;
            dictionary = (char **)realloc(dictionary, sizeof(char *) * (idx));
            *(dictionary+idx-1) = word;
            widx = 0;
            word = (char *)realloc(word, 0);
        }
        else if( c == '.' || c == ',' || c == '?' || c == '!' ){
            // skip
        }
        else{
            widx++;
            word = (char *)realloc(word, sizeof(char) * (widx));
            *(word + widx-1) = (char)c;
        }
    }
    fclose(fr);

    // print words
    int n = idx;
    for(i = 0; i < n; i++){
        printf("%d - %s \n", i, *(dictionary+i));
    }
    return 0;
}

输出:

0 - shellbly 
1 -  
2 - shellbly 
3 - Bourne-derived 
4 - shellbly 
5 - Bourne-derived 
6 - shellbly 
7 - Bourne-derived 

预期:

1 - The 
2 - original 
3 - Bourne 
4 - shell 
5 - distributed 
6 - with 
7 - V7 
8 - Unix 

我必须做错事。感谢您的任何反馈。

1 个答案:

答案 0 :(得分:1)

realloc(word, 0)相当于free(word)。但是,指针word与您刚存储为dictionary元素的指针相同,这意味着它不再有效访问dictionary的指针元素。

而不是word = realloc(word, 0);,你可以只做word = NULL;。这将导致下一个realloc分配新存储空间,并将指针留在dictionary中。

如果您担心正确清理分配的内存,那么稍后会free dictionary中的所有有效指针。