0

更新:这里基本上有两个问题:

  1. 如何将字符串数组传递给函数并在函数内访问它们。(这是通过2d 数组是双指针来解决的吗?
  2. 当数组的长度是可变的时如何做到这一点。使用符合 C99 的编译器与 Visual Studio MSVC 编译器。

第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.

我怎样才能使这项工作?

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);
}
4

0 回答 0