Hi I am slowly getting my head around pointers and indirection but am still having a little trouble.
In my main function i am creating an array of structs (computers) using malloc
int arraySize = 0;//This may be the first issue
Computer *ptrComputer = NULL;
ptrComputer = (Computer*) malloc(sizeof(Computer) * arraySize);
I am then passing the pointer to a function that reads data out of a file and into the array
arraySize = readFileToArray(&ptrComputer, arraySize);
int readFileToArray(Computer **compArray, int arraySize){
Computer newComp;
int foundARecord = 0;
/*File stuff*/
arraySize = extendArrays(compArray, arraySize, no_elements);
/*Use fscanf to read file data into the newComputer variable*/
printf("g %i\n", arraySize);
*compArray[arraySize - 1] = newComp;//set the newly created part of the array to newComputer
return arraySize;
}
int extendArrays(Computer **compArray, int arraySize){
arraySize++;
//Resize the computer array
*compArray = (Computer*)realloc(*compArray, (sizeof(Computer)*(arraySize + 1)));
return arraySize;
}
Now as far as i understand, i am passing the address of ptrComputer to the readFileToArray() function. It is then passing that same address to the extendArrays() function which resizes it. I am then trying to assign newComp to the location in memory that compArray points to. This works as long as i try to write to index 0 but any others cause xcode to throw an exc_bad_access error. This is all very confusing, can anyone with a bit of experience with this see where i am going wrong? It was working before when i was passing the actual pointer to the readFile function but it only worked once (think i was reallocating a copy of the pointer)
Any help would be very muchly appreciated
Thanks
malloc().reallocto*compArray, as it may returnNULL, in which case the former value of*compArrayis still valid.malloc. Casting the return value ofmallocserves no purpose and may hide errors the compiler would catch otherwise.