I have an array of type T which I pass as a pointer parameter to a function.
The problem is that I can’t write new data to this array properly, without getting memory violation at the second try.
In this code I read integers from a text file and pass them to the function (part of template class of type T), in order to append them to the array.
After I finish to append the integers, I want to use the same array back in the Main.
Does someone know what’s wrong with the code?
Thanks, Max
template<class T> int CFile<T>::read(T **apBuf, int aNum)
{
int readCounter = 0;
*apBuf = (T*)malloc(sizeof(T)*aNum);
for (int i = 0; i<aNum; i++)
{
T var = read();
if (var == NULL)
{
if (isEof)
{
return readCounter;
}
else
{
perror ("Error Reading File - Insufficient var type");
return -1;
}
}
else
{
*apBuf[i] = var;
readCounter++;
}
}
return readCounter;
}
This is parsed as if it was written:
This is obviously not what you want;
apBufis a pointer to a pointer to an array; you are treating it as a pointer to an array and you are dereferencing theith element of it. What you really mean is:*apBufgives you “the object pointed to byapBuf,” which is the array; then you obtain theith element of the array.That said, this is rather unusual: why not accumulate the data into a
std::vector<T>and return that from the function? Then you don’t have to worry about the explicit dynamic memory management. (Also, isTalways a pointer type? If not, thenvar == NULLmakes no sense.)