C语言 C:删除数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5899776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C: delete array
提问by Tom
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?
我是新来的。我想创建数组,然后删除它,然后再放入另一个数组。我该怎么做?
回答by Chad
If you are looking for a dynamic array in C they are fairly simple.
如果您正在寻找 C 中的动态数组,它们相当简单。
1) Declare a pointer to track the memory,
2) Allocate the memory,
3) Use the memory,
4) Free the memory.
1)声明一个指针来跟踪内存,
2)分配内存,
3)使用内存,
4)释放内存。
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));
上的信息calloc()可以发现在这里,同样的事情可以用完成malloc()的,而不是使用malloc(size * sizeof(int));
回答by NPE
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 */

