如何在 C 中完全删除一个数组,以便可以重新初始化它?

发布于 2024-11-05 08:43:46 字数 256 浏览 1 评论 0原文

如:如何恢复内存,并将数组删除到可以稍后在程序中再次初始化的程度?就像这样:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ゞ花落谁相伴 2024-11-12 08:43:46

你不能。使用方括号定义的数组(在函数1的范围之外)会直接编译到您的程序中,因此无法释放。但是,您可以通过再次写入初始内容来重新初始化它。如果您希望能够随意创建和销毁数组,则需要将其存储为指针并使用mallocfree

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 and free.

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.

南城追梦 2024-11-12 08:43:46

您不能销毁静态初始化的数组,因为它们的生命周期就是整个程序的生命周期。您可以随时分配更多静态数组 - 无需首先释放旧的静态数据。

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.

甜味拾荒者 2024-11-12 08:43:46

您不能任意销毁静态和/或函数局部对象。

唯一可以显式控制其生命周期的对象是那些动态分配的对象(例如使用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).

抱着落日 2024-11-12 08:43:46

使用“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(), and free().

Don't forget to #include <stdlib.h>!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文