C:删除数组

发布于 2024-11-05 04:02:22 字数 46 浏览 1 评论 0原文

我是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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

以往的大感动 2024-11-12 04:02:22

如果您正在寻找 C 语言的动态数组,它们相当简单。

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));

有关calloc()的信息可参见此处,可以使用 malloc() 完成相同的操作,只需使用 malloc(size * sizeof(int));

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));

梦萦几度 2024-11-12 04:02:22

听起来您在问是否可以在不同时间重复使用指针变量来指向不同的堆分配区域。是的,您可以:

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 */

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