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

バッファーは 1 つのポインターのみを保持します。次のようなものが必要です:

   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 に答える