Deallocating memory in main function that was malloc'd elsewhere.
The instructions for the program state that "The main program should deallocate the returned array when it's finished using it."
Which is slightly ambiguous, the function actually returns a pointer that points to the first element of an array that the function creates.
My main:
Code:
int main (void)
{
int c[] = {2,4,4,6};
printf("Reverse 2 returns: %i, which is the value of the pointer\n"
"that points to the first element in a new array containing the\n"
"elements of array c in reverse.\n", reverse2(c, 4));
printf("The dereferenced value it points to is: %i\n", *reverse2(c, 4));
free(temp);
system("pause");
}
My reverse2 function:
Code:
int* reverse2 (const int a[], int size)
{
int i;
int j=0;
int* temp;
temp=(int*)malloc(size*sizeof(int));
int* ptr=temp;
for (i=size-1; i>=0; --i)
{
temp[j]=a[i];
++j;
}
return ptr;
}
That returned an error:
error C2065: 'temp' : undeclared identifier
The program itself runs fine-- if I don't free the memory-- returning all the correct values. But if I want to free up the memory used to assign that new array and such it errors.
So I'm not sure how to de-allocate that memory (besides freeing it inside the reverse2 function but then the ptr is returned in the main function pointing to garbage) in the main function.
I tried a few different approaches but it just brain damaged the comp :)