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?
In C programming, an array is derived data that stores primitive data type values like int, char, float, etc. To delete a specific element from an array, a user must define the position from which the array's element should be removed. The deletion of the element does not affect the size of an array.
To delete the array's element using remove() method, first, we have to convert the array into an arraylist. Once the array is converted into an arraylist then we can utilize the remove() method of the Arraylist class to delete the array elements.
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.
Removing an element from Array using for loopWe can use for loop to populate the new array without the element we want to remove. The code removes the element at index 3. This method simply copies all the elements except the one at index 3 to a new array.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With