如果我创建一个大小为 10 的数组,并且数组中仅存储 2 个元素,那么剩余的空间就会被浪费。那么我该如何解决这个问题呢? (按数据结构)
最佳答案
您将使用一个简单的链表而不是数组,或者如果您需要使用数组,那么您应该使用 realloc()
,这会将数组缩小为仅使用 2 个单元,而不是 10 个。
,像这样:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int* ptr = malloc(10 * sizeof(int));
ptr[0] = 4;
ptr[1] = 13;
ptr = realloc(ptr, 2 * sizeof(int));
printf("%d %d\n", ptr[0], ptr[1]);
return 0;
}
输出:
4 13
关于c - 如何节省数组中未使用的空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45782503/