0

我正在使用 Netbeans8.0 在 C 中工作,我必须以迭代的方式读取文件以获取单词列表。也就是说,在单次迭代中,一个文件被读入一个字符串数组,然后将该数组合并到一个数组中。

void merge_array(char** a,int* M, char** b,int N)
{
    //............. Add  extra memory to a ..............*/
    void *tmp = realloc(a, (*M+N) * sizeof(*a));
    if (tmp == NULL)
    {
        perror("Merging -> Could not reallocate");
        exit(EXIT_FAILURE);
    }
    a = tmp;
    memset(a+(*M), 0, N*sizeof(*a));

     //............. copy strings in b to a ..............*/
    int i,j=0;
    for(i=*M; i<((*M)+N); i++)
    {
        size_t wlen = strlen(b[j]);
        a[i] = malloc((wlen+1) * sizeof(char));
        if (a[i] == NULL)
        {
            perror("Failed to replicate string");
            exit(EXIT_FAILURE);
        }            
        memcpy(a[i], b[j], wlen+1);
        j++;
    }

    (*M) = (*M)+N;                // resetting the count

    printf("Confirm - %s, %d\n",a[0],*M);
}

上面的函数读取文件的内容。在 main 中,上面的函数被迭代调用并合并到一个名为“termlist”的数组中。主要代码如下

char** termlist;
int termCount=0;
while(files[i]){        
    char **word_array;        
    int wdCnt,a;

    char* tmp = (char*) malloc(strlen(path)*sizeof(char));
    strcpy(tmp,path);   strcat(tmp,files[i]);   strcpy(files[i],tmp);

    printf("\n\n******* Reading file %s...\n",files[i]);  
    word_array = getTerms_fscanf(files[i],&a);      //reading contents of file  

    wdCnt = a;
    if(i==0)    // before reading the first file initializing the termlist
    {
        termlist = (char**) malloc(wdCnt*sizeof(char*));
    }            
    merge_array(termlist,&termCount,word_array,wdCnt);      
    printf("CHECK - %s, %d\n",termlist[0],termCount);

    free(word_array);
    ++i;
} 

现在的问题是,在第一次两次迭代之后,内部函数一切正常,但在 termlist[0] 的主要值中,termlist[1] 原来是垃圾。这是从第一个文件读取的前 2 个单词丢失了。第 3 次迭代在 merge_array 函数调用时返回失败。

输出是

******* Reading F:/Netbeans C/Test Docs/doc1.txt...
Confirm - tour, 52
CHECK - tour, 52

******* Reading F:/Netbeans C/Test Docs/doc2.txt...
Confirm - tour, 71
CHECK - Ôk'aÔk'a`œ€`œ€äk'aäk'aìk'aìk'aôk'aôk'aük'aük'ah“€, 71

我无法确定这个问题..请帮助解决这个问题..

4

0 回答 0