2010-03-05 77 views
1

我從來沒有用malloc來存儲超過值,但我不得不使用strdup命令輸入文件的行,我沒有辦法讓它工作。使用strdup進入malloc保留空間

我雖然使用strdup()來獲取指向每行的指針,然後根據使用malloc()保留的行數將每個指針放入一個空間。

我不知道我是否需要像保留內存那樣做一個數組指向指針,我的意思是使用char**,後來把每個指針指向保留空間中的每個strdup。

我雖然是這樣的:

char **buffer; 
char *pointertostring; 
char *line; // line got using fgets 

*buffer = (char*)malloc(sizeof(char*)); 
pointertostring = strdup(line); 

我不知道以後該怎麼辦,我甚至不知道這是正確的,在這種情況下,我應該怎麼辦存儲指向緩衝區位置的字符串?

Regards

回答

2

如果我正確理解你的要求。你將不得不這樣做:

char **buffer; 
char line[MAX_LINE_LEN]; // line got using fgets 
int count; // to keep track of line number.  

// allocate one char pointer for each line in the file. 
buffer = (char**)malloc(sizeof(char*) * MAX_LINES); 

count = 0; // initilize count. 

// iterate till there are lines in the file...read the line using fgets. 
while(fgets(line,MAX_LINE_LEN,stdin)) { 
    // copy the line using strdup and make the buffer pointer number 'count' 
    // point to it 
    buffer[count++] = strdup(line); 
} 
.... 
.... 
// once done using the memory you need to free it. 
for(count=0;count<MAX_LINES;count++) { 
    free(buffer[count]); 
} 
.... 
.... 
0

你的緩衝區只保存一個指針。你需要這樣的東西:

char **buffer; 
    char *pString; 
    int linecount; 

    buffer = (char **)malloc(sizeof(char *)*MAXIMUM_LINES); 
    linecount = 0; 

    while (linecount < MAXIMUM_LINES) { 
     pString = fgets(...); 
     buffer[linecount++] = strdup(pString); 
    } 
+0

之後,我使用realloc來適應分配的空間。謝謝! – sui 2010-03-05 13:27:18