更新:这里基本上有两个问题:
第2点的答案是:
MSVC编译器当前不允许将数组长度设置为函数签名中的参数,如下所示,尽管对于符合C99的编译器而言这是正常的。
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.
。< / p>
我该如何做到这一点?
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);
}