如何在 C 中完全删除一个数组,以便可以重新初始化它?
如:如何恢复内存,并将数组删除到可以稍后在程序中再次初始化的程度?就像这样:
char * array[][2] = {
{"bla","bla","bla"},
{"blabity","blabity","bla"}
}
// Delete array
sizeof(array) == NULL;
char * array[][2] = {
{"bla","bla","bla"},
{"blabity","blabity","bla"}
}
As in: How do you recover the memory, and delete the array to such an extent you can initialize it again later in the program? Like so:
char * array[][2] = {
{"bla","bla","bla"},
{"blabity","blabity","bla"}
}
// Delete array
sizeof(array) == NULL;
char * array[][2] = {
{"bla","bla","bla"},
{"blabity","blabity","bla"}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能。使用方括号定义的数组(在函数1的范围之外)会直接编译到您的程序中,因此无法释放。但是,您可以通过再次写入初始内容来重新初始化它。如果您希望能够随意创建和销毁数组,则需要将其存储为指针并使用
malloc
和free
。1:在函数内,数组将在每次函数运行时在堆栈上创建,并在函数退出时销毁,除非它被定义为静态变量。您仍然无法在不返回的情况下取消分配它。
You can't. An array defined using brackets (outside the scope of a function1) is compiled directly into your program, and therefore cannot be deallocated. You can, however, reinitialize it simply by writing the initial contents to it again. If you want to be able to create and destroy an array at will, you need to store it as a pointer and use
malloc
andfree
.1: Within a function, the array will be created on the stack each time the function is run, and destroyed when it exits, unless it is defined as a static variable. You still cannot deallocate it without returning.
您不能销毁静态初始化的数组,因为它们的生命周期就是整个程序的生命周期。您可以随时分配更多静态数组 - 无需首先释放旧的静态数据。
You cannot destroy a statically initialized array, because their lifetime is the lifetime of the whole program. You can trivially allocate more static arrays at any time- there's no need to deallocate your old static data first.
您不能任意销毁静态和/或函数局部对象。
唯一可以显式控制其生命周期的对象是那些动态分配的对象(例如使用
malloc
)。You cannot arbitrarily destroy static and/or function-local objects.
The only objects whose lifetime you can explicitly control are those that are dynamically allocated (e.g. with
malloc
).使用“malloc系列”:
malloc()
,calloc()
, < a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html" rel="nofollow">realloc()
和free()
。不要忘记
#include
!Use the "malloc family":
malloc()
,calloc()
,realloc()
, andfree()
.Don't forget to
#include <stdlib.h>
!