UPDATE: There are essentially two issues here:
- How to pass an array of strings to and access them inside a function. (This is solved by Is 2d array a double pointer?
- How to do this when the length of the array is variable. Using C99 compliant compiler vs Visual Studio MSVC compiler.
The answer to point 2 is:
MSVC compiler currently does not allow the array length to be set as a parameter in the function signature as below although this would be OK with a C99 compliant compiler.
void ReadItems(FILE * pFile, size_t numBytes, char stringArrayOut[][numBytes+1], int numberOfItems)
To make it work in VS 2015 I copied the pointer and incremented to the next string manually using pointer arithmetic:
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;
}
}
What is the correct way to create an array of empty C strings, pass them to a function and have the function fill the strings?
In my usecase I want to read some strings from a file and put them into the array.
Inside ReadItem
function I read the text from the file successfully into readBuff
, but when I try to copy the string into stringOut
I get the error Access violation writing location 0x00000000.
.
How can I make this work?
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);
}