How can I delete a matrix?

Started by
4 comments, last by Carolina 18 years, 8 months ago
Hi there! I have a simple question today...How can I delete a dynamically allocated matrix in C?I know in C++ I´d simply use delete,but in C I must use free().How should I do this?=/ Thanks, Carol
Advertisement
/* make it */int* mtx = (int*) malloc(SZ*SZ*sizeof int));/* use it */.../* throw it away */free (mtx);


[wink]
Huh...but then won´t the matrix be just a big vector? I used malloc like this to allocate:

int **matrix;/*Pointer to pointer*/

matrix=(int**)malloc(m*sizeof(int*));
for(i=0;i<m;i++)
{
matrix=(int*)malloc(n*sizeof(int));
}

This turned out to be at least usable when using a matrix[m][n],but I really don´t know how to use free() on it. And I must do this on a linked list that is also a matrix o.O Like,imagine the first line of a matrix as the head nodes of linked lists:

head head head head (Line 1)
| |
node node .......
| |
node node ......
: : :
. . .

How can I delete this whole thing using free()?
Yes, it would be a big vector, but it is kind of easier to work with. Anyway:

for (int i = 0; i < m; i++){	free(matrix);}free(matrix);


As for the linked list, you will have to iterate through every link and call free on the pointer.
[ search: google ][ programming: msdn | boost | opengl ][ languages: nihongo ]
Generally, you deallocate something in a manner which is parallel to how you allocate it. For the "pointer to array pointers" approach in C++, you would new[] the base dimension, and then new[] each "row" of the matrix. Therefore to deallocate it, you would follow the steps in reverse: delete[] the rows, then delete[] the base dimension.

In C code it is exactly the same, except with malloc and free.

There are three real semantic differences here that I can think of:

1) C malloc and free will not invoke constructors or destructors (respectively), because they don't exist in C. Therefore if you use malloc and free and pass the code to a C++ compiler, they still won't, for compatibility.
2) For malloc, you need to do the size calculation yourself (and you lose a little bit of type safety).
3) The malloc and free calls do not provide a distinction between single object and array allocations. This looks cleaner, but is not really much simpler - the complexity is shifted to the size calculation (see (2)). Meanwhile, the lack of information here deprives the compiler of some optimization opportunities. In particular, because the size of a single object allocation is known at compile-time, it might not be stored at runtime. (This is one of the many reasons that you must use delete for new and delete[] for new[], although of course the best reason is "because the standard says not doing so yields undefined behaviour".)
Thanks for answering,I really prefer using new and delete.^_^

This topic is closed to new replies.

Advertisement