C -- Reading from file into array of char*
C only.
First em I on the right track? I am just trying to read line by line and store each line into a char**.
It works, but maybe I missed something MUCH simpler.
PHP Code:
char ***ppNames; // <-- this is a parameter for the function thats why you see the extra dereference
//Begin reading the file
int iLine = 0;
while (!feof(pFile)) {
//Read in the name
char pName[255];
fgets(pName, 255, pFile);
char *pNewLinePos = strrchr(pName, '\n');
if (pNewLinePos != NULL) {
(*pNewLinePos) = '\0';
}
//Reallocate and zero the new memory
(*ppNames) = (char**)realloc((*ppNames), (iLine+1) * (sizeof(char**)));
memset((*ppNames)+iLine, 0, sizeof(char*));
//Reallocate a new char pointer
(*ppNames)[iLine] = (char*)realloc((*ppNames)[iLine], strlen(pName));
//Copy in the name into the char array
strcpy((*ppNames)[iLine], pName);
//Next Line
iLine++;
}
Second, I am trying to free the array of char* and em getting errors:
PHP Code:
for (i = 0; i < iSize; i++) {
free(*(ppNames+i)); //Causes error, invalid pointer deletion
free(ppNames+i); //Works fine
}
Any advice?
Re: C -- Reading from file into array of char*
There is almost NEVER a time when you need to 0 memory.
Re: C -- Reading from file into array of char*
Yes but I found one. Realloc, if the ptr* you pass in is not NULL it will try to resize the memory location. Of course in the above example if the memory is not zero'd then a Segmentation Fault will occur because the next realloc() will try and resize an invalid pointer.
I could prolly just set it to zero lol. Now that I look it over.