我试图创建使用realloc完成的动态增长数组。我在下面有示例,但是我不了解使用malloc的代码是如何工作的。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int cnt = 0;
double *numbers = NULL;
double newnum;
while (scanf("%lf", &newnum) == 1 && newnum != -1) {
double *newarr = (double*) malloc(sizeof(double) * (cnt+1));
for (int i = 0; i < cnt; ++i)
newarr[i] = numbers[i];
free(numbers);
numbers = newarr;
numbers[cnt] = newarr;
++cnt;
}
for (int i = cnt-1; i >= 0; --i) {
printf("%f\n", numbers[i]);
}
free(numbers);
return 0;
}
答案 0 :(得分:2)
realloc()
与malloc()
,memcpy()
,free()
都是同一功能(*)。
代码中的循环有效地替换了memcpy()
// memcpy(newarr, numbers, cnt * sizeof *newarr);
for (int i = 0; i < cnt; ++i)
newarr[i] = numbers[i];
(*) realloc()
可能很聪明,可以避免使用memcpy()
和free()
并重新使用内存。
如何在我的代码中实现呢?
它有助于将指针和全部/已使用元素封装在结构中。
#include <stdio.h>
#include <stdlib.h>
struct DynArray {
double *data;
size_t m; // total
size_t n; // used
};
void growarray(struct DynArray *x) {
size_t newsize = x->m * 13 / 8 + 1; // use phi aproximation 13/8
double *newarr = realloc(x->data, newsize * sizeof *x->data);
if (!newarr) exit(EXIT_FAILURE);
fprintf(stderr, "INFO: realloc'ed with %d elements.\n", (int)newsize);
x->data = newarr;
x->m = newsize;
}
int main(void) {
struct DynArray numbers = { 0 };
double newnum;
while (scanf("%lf", &newnum) == 1 && newnum != -1) {
if (numbers.n == numbers.m) growarray(&numbers);
numbers.data[numbers.n] = newnum;
numbers.n++;
}
for (int i = numbers.n - 1; i >= 0; --i) {
printf("%f\n", numbers.data[i]);
}
free(numbers.data);
return 0;
}
See code running on ideone或previous version without growarray function或previous version with cnt