|
-
Mar 20th, 2006, 11:43 PM
#1
Thread Starter
PowerPoster
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?
"From what was there, and was meant to be, but not of that was faded away." - - Steve Damm
"The polar opposite of nothingness is existance. When existance calls apon nothingness it shall return to nothingness." - - Steve Damm
"When you do things right, people won't be sure if you did anything at all." - - God from Futurama
-
Mar 21st, 2006, 08:05 AM
#2
Frenzied Member
Re: C -- Reading from file into array of char*
There is almost NEVER a time when you need to 0 memory.
-
Mar 21st, 2006, 11:59 AM
#3
Thread Starter
PowerPoster
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.
"From what was there, and was meant to be, but not of that was faded away." - - Steve Damm
"The polar opposite of nothingness is existance. When existance calls apon nothingness it shall return to nothingness." - - Steve Damm
"When you do things right, people won't be sure if you did anything at all." - - God from Futurama
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|