问题在于运算顺序:n + 1 * sizeof(int) 的意思是“乘以 sizeof(int) 的 1 倍,然后加上 n”。您可以使用括号来强制执行顺序:(n + 1) * sizeof(int)。
内存分配可能很昂贵!请求合理的内存块,然后每隔一段时间将其增加 2 倍。在内存分配系统调用中,操作系统可能会为您提供比您要求的更大的块,以便后续的 realloc 调用更便宜并使用您的程序已经可用的内存。
最好检查您的malloc 和realloc 调用是否成功。如果分配请求失败,这些函数将返回 NULL。
另外,当你完成分配的内存时,不要忘记free 以避免内存泄漏。
编写您自己的类似“vector/ArrayList/list”的接口可能是一个有趣的练习,该接口可以扩展和收缩到大小并可能具有slice(start_index, end_index) 和remove(index) 等操作。
这是一个完整的例子:
#include <stdio.h>
#include <stdlib.h>
int main() {
int nums_len = 0;
int nums_capacity = 5;
int *nums = malloc(nums_capacity * sizeof(int));
while (scanf("%d", &nums[nums_len]) != -1) {
if (++nums_len >= nums_capacity) {
printf("increasing capacity from %d to %d\n",
nums_capacity, nums_capacity * 2);
nums_capacity *= 2;
nums = realloc(nums, nums_capacity * sizeof(int));
if (!nums) {
fprintf(stderr, "%s: %d: realloc failed\n",
__func__, __LINE__);
exit(1);
}
}
printf("got: %d\n", nums[nums_len-1]);
}
printf("Here are all of the %d numbers you gave me:\n", nums_len);
for (int i = 0; i < nums_len; i++) {
printf("%d ", nums[i]);
}
puts("");
free(nums);
return 0;
}
示例运行:
5
got: 5
6
got: 6
7
got: 7
8
got: 8
1
increasing capacity from 5 to 10
got: 1
3
got: 3
5
got: 5
6
got: 6
7
got: 7
1
increasing capacity from 10 to 20
got: 1
2
got: 2
3
got: 3
4
got: 4
5
got: 5
6
got: 6
67
got: 67
8
got: 8
1
got: 1
2
got: 2
3
increasing capacity from 20 to 40
got: 3
4
got: 4
1
got: 1
2
got: 2
Here are all of the 23 numbers you gave me:
5 6 7 8 1 3 5 6 7 1 2 3 4 5 6 67 8 1 2 3 4 1 2