更新:ここには本質的に2つの問題があります:
- 関数内で文字列の配列を渡し、それらにアクセスする方法。(これはIs 2d array a double pointer?によって解決されます。
- 配列の長さが可変の場合にこれを行う方法。C99 準拠のコンパイラと Visual Studio MSVC コンパイラの使用。
ポイント2への答えは次のとおりです。
C99 準拠のコンパイラでは問題ありませんが、MSVC コンパイラでは現在、以下のように配列の長さを関数シグネチャのパラメータとして設定することはできません。
void ReadItems(FILE * pFile, size_t numBytes, char stringArrayOut[][numBytes+1], int numberOfItems)
VS 2015 で機能させるために、ポインターをコピーし、ポインター演算を使用して手動で次の文字列にインクリメントしました。
void ReadItems(FILE * pFile, size_t numBytes, char * ptr_stringArrayOut, int numberOfItems)
{
char * ptr_nextString = ptr_stringArrayOut;
for (int i = 0; i < numberOfItems; i++) {
ReadItem(pFile, numBytes, ptr_nextString);
if (i >= numberOfItems - 1) break;
ptr_nextString += numBytes;
}
}
空の C 文字列の配列を作成し、それらを関数に渡し、関数に文字列を入力させる正しい方法は何ですか?
私のユースケースでは、ファイルからいくつかの文字列を読み取り、それらを配列に入れたいと考えています。
関数内ReadItem
でファイルからテキストを正常に読み取りましたreadBuff
が、文字列をにコピーしようとするとstringOut
エラーが発生しますAccess violation writing location 0x00000000.
。
どうすればこれを機能させることができますか?
int main(void){
/* Declare and initialize an array of 10 empty strings, each string can be
up to 16 chars followed by null terminator ('\0') hence length = 17. */
char myArrayOfStrings[10][17] = { "","","","","","","","","","" };
//Open file
FILE *pFile = fopen("C:\\temp\\somefile.ext", "r");
if (pFile == NULL) { printf("\nError opening file."); return 2; }
// myArrayOfStrings should contain 10 empty strings now.
ReadItems(pFile, 16, myArrayOfStrings, 10);
// myArrayOfStrings should now be filled with the strings from the file.
}
void ReadItems(FILE * pFile, size_t numBytes, char **stringArrayOut, int numberOfItems)
{
for (int i = 0; i < numberOfItems; i++) {
ReadItem(pFile, numBytes, stringArrayOut[i]);
}
}
void ReadItem(FILE * pFile, size_t numBytes, char * stringOut){
int numBytesRead = 0;
char readBuff[201] = { 0 };
if (numBytes > 200) numBytes = 200;
numBytesRead = fread (readBuff, 1, numBytes, pFile);
strcpy(stringOut, readBuff); /* ERROR: Access violation writing location 0x00000000. */
printf("\n# bytes: %d \t", numBytesRead);
printf("%s", numBytes, stringOut);
}