我正在尝试用 C 解决以下练习:
"Consider a function dobuleArray() that takes in input an array and a pointer to its size and gives as output the array doubled. Create an array of size 1 to 4 as initial size. Then, start filling the array with 2048 randomly generated integers; each time the array is full, call the doubleArray() function. After each invocation of doubleArray() , print again the content of the array"
我在初始大小为 3 时遇到问题。我编写的程序不适用于大于 4 的数字,我也不知道为什么。准确地说,我得到一个 realloc: invalid next size
int* doubleArray(int* vect, int* dim) {
int old_dim = *dim;
int i;
int new_dim = old_dim * 2;
vect = realloc(vect, new_dim * sizeof(int));
for (i = old_dim; i < new_dim; i++) {
vect[i] = 0;
}
*dim = new_dim;
return vect;
}
int main() {
int n = 3;
int* size = &n;
int* arr = malloc(n * sizeof(int));
for (int i = 0; i < 2048; i++) {
if (i > *size) {
int j = 0; // used to count the size of the doubled-array each time the
// if condition is true
arr = doubleArray(arr, size);
for (int i = 0; i < *size; i++) {
j++;
printf("%d ", arr[i]);
}
printf("\n");
printf("%d\n", j);
printf("\n");
arr[i] = rand() % 6;
} else {
arr[i] = rand() % 6;
}
}
}
我认为 double 函数应该可以正常工作。整个程序实际上只适用于 2048 % value == 0
这样的值。但我想应该有一种方法可以更正它以使其适用于 3。
明确地说,该程序的输出如下所示:
1 4 3 0 0 0
6
realloc(): invalid next size
signal: aborted (core dumped)
最佳答案
您写入数组末尾,这会导致未定义的行为。 (在这种情况下非常烦人的未定义行为)
if (i > *size) {
应该是
if (i >= *size) {
关于arrays - 动态加倍数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69698189/