Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: delete array

Tags:

c

I'm new in c. I want to create array, and after it delete it, and then put another array into it. How can I do it?

like image 523
Tom Avatar asked Oct 21 '25 09:10

Tom


2 Answers

If you are looking for a dynamic array in C they are fairly simple.

1) Declare a pointer to track the memory,
2) Allocate the memory,
3) Use the memory,
4) Free the memory.

int *ary; //declare the array pointer
int size = 20; //lets make it a size of 20 (20 slots)

//allocate the memory for the array
ary = (int*)calloc(size, sizeof(int));

//use the array
ary[0] = 5;
ary[1] = 10;
//...etc..
ary[19] = 500;

//free the memory associated with the dynamic array
free(ary);

//and you can re allocate some more memory and do it again
//maybe this time double the size?
ary = (int*)calloc(size * 2, sizeof(int));

Information on calloc() can be found here, the same thing can be accomplished with malloc() by instead using malloc(size * sizeof(int));

like image 71
Chad Avatar answered Oct 23 '25 22:10

Chad


It sounds like you're asking whether you can re-use a pointer variable to point to different heap-allocated regions at different times. Yes you can:

void *p;         /* only using void* for illustration */

p = malloc(...); /* allocate first array */
...              /* use the array here   */
free(p);         /* free the first array */

p = malloc(...); /* allocate the second array */
...              /* use the second array here */
free(p);         /* free the second array */
like image 20
NPE Avatar answered Oct 23 '25 22:10

NPE