簡體   English   中英

C動態分配,並重新分配一個字符**

[英]C dynamic allocation with realloc of a char**

我是新來的,英語說得不太好。 我有一個關於我的代碼的問題(用C語言編寫)。

代碼應該做什么:存在一個名為“ g.txt”的文件,應該打開該文件。 然后,它逐行讀取並在緩沖區( zpuffer[200] )中復制每一行,此后,應使用strcpy將緩沖區的內容復制到**Dfile **Dfile指向一個char* ,它的空間首先被malloc分配。 如果**Dfile沒有足夠的空間來保存,則代碼將執行realloc ,以騰出更多的可用空間。

第一次調用realloc ,實際上我有更多空間! 但是第二次,它沒有用。 操作系統Ubuntu,用德語說:“ Bus-Zugriffsfehler(Speicherabzug geschrieben)”。 英語:“總線訪問錯誤(寫入的轉儲)”

這是我的代碼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define OBJS 10 //new Lines a one time for **Dfile

int main(void){
FILE *datei;
datei=fopen("g.txt", "r");
if (datei == NULL){
    fprintf(stderr, "\nFEHLER\n");
    return 1;
}

char zpuffer[200]; //buffer
char **Dfile; //save content of g.txt line by line, every line has its own index

int zeilen = 0; //the actual amount of lines
int speicher = 0; //total indices in **Dfile    
Dfile = (char**)malloc(sizeof(char**)*(speicher + OBJS));
speicher += OBJS;   

while (fgets(zpuffer, 199, datei) != NULL){ 
    if (speicher <= zeilen){//speicher <= zeilen --> allocate memory
        Dfile = (char**)realloc(*Dfile, sizeof(char**)*(speicher + OBJS)); //!!ERROR!! but just the second time!!
        if (Dfile == NULL){
            fprintf(stderr, "\nFEHLER Alloc\n");
            return 1;
        }           
        speicher += OBJS;
    }

    Dfile[zeilen]=malloc(strlen(zpuffer)+1);
    strcpy(Dfile[zeilen++], zpuffer);       
    printf("%s", Dfile[zeilen - 1]);    
}
return 0;
}

有人可以幫我嗎?

您將*Dfile傳遞給realloc()

您是否打算通過Dfile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM