あなたは、配列の行として、ファイルの各行を保存char
の2次元配列を使用する場合:あなたは、フロントまで持っているどのように多くの行がわからない場合
char fileContents[NUM_LINES][LINE_LENGTH + 1]; // +1 for zero terminator
、あなたをいくつかのメモリ管理が必要です。まず、最初のエクステントを割り当てる必要があります。
#define INITIAL_EXTENT 20 // or some good starting point
char (*fileContents)[LINE_LENGTH + 1] = malloc(sizeof *fileContents * INITIAL_EXTENT);
if (!fileContents)
{
// malloc failed; fatal error
fprintf(stderr, "FATAL: could not allocate memory for array\n");
exit(EXIT_FAILURE);
}
size_t numRows = INITIAL_EXTENT; // number of rows in array
size_t rowsRead = 0; // number of rows containing data
ファイルを読み込むときに、配列に空きがあることを確認します。そうでない場合は、realloc
呼び出しを使用して配列を拡張する必要がありますが、これは潜在的に高価な操作です。一般的な手法は、配列を拡張するたびに配列のサイズを2倍にすることです。これにより、realloc
呼び出しの総数が最小限に抑えられます。もう1行必要であるため配列サイズを2倍にすると内部的な断片化が起こる危険がありますが、それは恐らく解析できるものです:
char tmpBuf[LINE_LENGTH + 2]; // account for newline in input buffer
while (fgets(tmpBuf, sizeof tmpBuf, inputFile))
{
/**
* Check to see if you have any room left in your array; if not,
* you'll need to extend it. You'll probably want to factor this
* into its own function.
*/
if (rowsRead == numRows)
{
/**
* Use a temporary variable for the result of realloc in case of failure
*/
char (*tmp)[LINE_LENGTH + 1] =
realloc(fileContents, sizeof *fileContents * (2 * numRows));
if (!tmp)
{
/**
* realloc failed - we couldn't extend the array any more.
* Break out of the loop.
*/
fprintf(stderr, "ERROR: could not extend fileContents array - breaking out of loop\n");
break;
}
/**
* Otherwise, set fileContents to point to the new, extended buffer
* and update the number of rows.
*/
fileContents = tmp;
numRows *= 2;
}
// strip the newline from the input buffer
char *newline = strchr(tmpBuf, '\n');
if (newline)
*newline = 0;
strcpy(fileContents[rowsRead++], tmpBuf);
}
http://stackoverflow.com/questions/3536153/c -dynamically-growing-array – Jay
2D配列を動的に割り当てる方法やサイズを変更する方法は不思議ですか? 'char(* arr)[CHARS_PER_LINE] = malloc(sizeof(* arr)* NUM_LINES);'多分? – Dmitri
あなたの例では、最初の行に "(改行)"がありますが、2番目の行にはありません。それは意図的なものか、見落としなのか、それとも何ですか? – chux