Reputation: 91
I'm new to C and I'm wondering if it is possible to delete a whole array, not just an element, in C?
In C++ there is the delete[]
, is there something similar in C?
Upvotes: 7
Views: 32194
Reputation: 43518
1) If the declartion of your array was done in this way:
int A[20];
Your array could not be deleted because it's allocated statically
2) If the declartion of your array was done in this way:
int *A=malloc(20 * sizeof(int));
//or
int *A=calloc(20, sizeof(int));
Your array could be deleted with free(A)
because it's allocated dynamically
Upvotes: 10
Reputation: 2420
When you allocate memory in C using malloc
, some extra information is stored after (or before) the allocated chunk. free
uses this information to know how much memory you allocated in the first place and will free the entire chunk.
So if you allocated only a single element, for example a struct, it will only free one element. If you allocated an entire array of struct, it will free the entire thing.
In C++, you use new
and new []
instead of malloc, which initializes values using constructor. Which is why there are two distinct delete
: one for single value (delete
), and one for arrays (delete []
).
Upvotes: 3
Reputation: 234
In C, if you are declaring your array as static ex: int a[10], no need to delete. It will be freed when your function ends or program terminates. If you have allocated memory using any of memory allocation techniques[malloc,calloc], since it is allocated by you, should be freed by yourself and you use free(ptr) for freeing allocated memory block.
Upvotes: 0
Reputation: 1305
Creation of the tab : malloc or calloc functions. And then free function to deallocate it
Upvotes: 0
Reputation: 42175
You can just use free
to delete a dynamically allocated array.
int* array = malloc(10*sizeof(int));
...
free(array);
If you allocated memory for each array element, you'll also need to free
each element first.
char** array = malloc(10*sizeof(char*));
for (int i=0; i<10; i++) {
array[i] = malloc(i);
}
....
for (int i=0; i<10; i++) {
free(array[i]);
}
free(array);
Upvotes: 7
Reputation: 399833
If you've allocated the array dynamically (with malloc()
), you just use free()
to de-allocate it. Then you can no longer access the pointer, since you no longer "own" the memory.
Upvotes: 1
Reputation: 105886
If you used malloc()
/calloc
simply use free()
:
type * ptr = malloc(n * sizeof(type));
if(ptr == NULL)
couldnt_allocate_memory();
/* ... */
free(ptr);
Upvotes: 0
Reputation: 23699
In C++, you don't call delete
unless you've used new
. If you didn't use dynamic allocation, you don't free the memory.
In C, have a look at malloc
and free
if you want to control the lifetime of your arrays.
#include <stdlib.h>
int *array = malloc (size_in_bytes);
/* Some stuff. */
free (array); /* When I don't need it anymore. */
Otherwise, automatic variables are automatically released.
Upvotes: 0