0

I am pointing to the address of a 2D array, and I am confused as to how to dereference the pointer to free up the memory again. (I don't use "->" or "*". Is that wrong?)

My code:

double array[12][12];
//filled with numbers

double *arrayPtr; //pointer

arrayPtr = &array[0][0]; //pointing to address

multiply(arrayPtr, arrayPtr); //this works fine

//Do I need to do anything further to make sure my memory management is correct?  And if so, why?
4

3 回答 3

4

In this case, the answer is no -- since you simply defined array (didn't use something like malloc to allocate it) you don't have to do anything to free it either. If it was local (defined inside a function) it'll be freed automatically when you exit the function. If you defined it outside any function, it's a global, so it'll exist the entire time the program runs. Either way, you don't have to d any explicit memory management.

于 2012-05-23T23:09:33.903 回答
2
double array[12][12];

You're declaring array on the stack. It's not dynamically allocated with the heap, so you don't "free up the memory".

double *arrayPtr; //pointer
arrayPtr = &array[0][0]; //pointing to address

If you want to point to the first element, this would suffice:

double* arrayPtr = array;
于 2012-05-23T23:09:48.527 回答
0

First, there a quite different between C and C++

In C to use memory management you shall use malloc/calloc/realloc and free. In c++ you will use new and delete.

In your code.

double array[12][12];

This is imply to allocate memory in stack. So the memory will be allocated to the scope of this program section so that it will be green when the scope of this variable end.

If you will to use free you will need

 double **array;
 array = (double **) malloc(sizeof(double*));
 *array = (double*) malloc (24 * sizeof(double));

free (*array);
free (array);
于 2012-05-23T23:29:40.827 回答