arrays - 动态加倍数组

标签 arrays c realloc

我正在尝试用 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/

相关文章:

比较数组中的三个数字

c - 使用指针在函数内部定义数组

c - 当 2 个指针指向同一区域并且其中 1 个被释放时会发生什么?

c - 如何在 main 中调用带有 argc 和 argv 的链接列表?

c - 为什么变量值经过两次循环递增后就达到了5050? (循环到100)

c - 从数组读取段错误(可能与 malloc/realloc 相关)

c - 使用 "calloc"和 "realloc"

php - 将MYSQL结果拆分为4个数组

python - 在 NumPy 中使用字符串作为数组索引

c - 在 CUDA 中倾斜图像