Hiya, I'm brand new to C so I'm still trying to get my head around what functions etc are available, and the concept of pointers and memory management.
What I'm trying to do is create an array of strings read from a file, but I'm having a few issues with realloc.
I read that if you use realloc, there's a possibility that the addresses of the "stuff" will change, problem being that I've already made a bunch of pointers to the original malloc'd stuff.
Is there any (easy) way to keep my pointers pointing to the right place after realloc? Or should I completely rethink the whole process?
Here's what I have so far (any tips or corrections would be much appreciated)
Code:
FILE *file;
char *filetext=NULL, *pfiletext=NULL;
char **array=NULL, **pArray=NULL;
int i=0, c=0, j=0, memoryBlock=50;
// i = reusable counter for loops
// c = number of elements in array
// j = number of characters read from file
if (!(file = fopen("sample.txt", "r"))) exit(0); //open file
if(!( filetext = calloc(MAXSIZE, sizeof(char)) )) exit(0);
j=fread(filetext, sizeof(char), MAXSIZE, file);
filetext[j]='\0';
fclose(file);
if(j==0)
{
puts("Something bad happened :(");
exit(0);
}
if(!(filetext = realloc(filetext, j++))) exit(0);// fix memory for filesize
if(!( array = calloc(memoryBlock+1,sizeof(char*)) )) exit(0); // array memory
//make pointers point at something
pfiletext = filetext;
pArray = array;
while(1)
{
if(c==0) // First iteration
{
*pArray = pfiletext;
pArray++;
c++;
}
if(c>memoryBlock)
{
memoryBlock = memoryBlock + 50;
if(!(array = realloc(array, 1+((sizeof(char*)*memoryBlock))))) exit(0); // array memory
//something needs to go here but I don't know what!!==========================================
}
if(!(pfiletext = strchr(pfiletext, '\n'))) break;
*pfiletext='\0';
pfiletext=pfiletext++;
*pArray=pfiletext;
pArray++;
c++;
}