1

我从来没有使用 malloc 来存储超过值,但我必须使用 strdup 来对输入文件的行进行排序,但我没有办法让它工作。

我虽然使用strdup()获取指向每一行的指针,然后根据保留的行数将每一行放入一个空间中malloc()

我不知道我是否必须这样做,就像保留内存是指向指针的数组一样,我的意思是使用char**然后将每个指向每个 strdup 的指针放入保留空间。

我虽然是这样的:

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

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

我不知道之后该怎么办,我什至不知道这是否正确,在那种情况下,我应该怎么做才能将指向字符串的指针存储在缓冲区的位置?

问候

4

2 回答 2

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]);
}
....
....
于 2010-03-05T12:38:27.713 回答
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);
   }
于 2010-03-05T12:35:47.143 回答