2010-03-05 78 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