c - 在 C 中动态增加数组大小

标签 c arrays dynamic-arrays

我需要根据用户输入增加 2 个数组的长度。我正在使用下面的代码。但是输出与用户输入不匹配。

    #include<stdio.h>        
    int main()
    {
        int i=0, key=0, size[key], time[key];

        while (key!=-1)
        {
             printf("Insert value for size : ");
             scanf("%d",&size[i]);
             printf("Insert value for time : ");
             scanf("%d",&time[i]);
             i++;

             printf("Run again Press-1 or Exit  : ");
             scanf("%d",&key);
        }

        int x=0;
        for (x ; x<i ; x++)
        {
             printf("%d %d\n",size[x],time[x]);
        }
        return 0;
    }

当用户输入值时:

    35 4
    20 3
    40 1
    60 7
    20 8

然后这是输出:

    8  4
    20 3
    40 1
    60 7
    20 8

如果数组长度超过 4,time 数组的最后一个元素将被打印为 size 数组的第一个元素。

为什么我的程序会给出这个输出?

最佳答案

让您入门的东西。

使用realloc() 重新调整指针指向的内存指针的大小。

#include <stdlib.h>        
#include <stdio.h>        

int main(void) {
  // Start with NULL and a size of 0
  int *my_time = NULL;
  size_t sz = 0;

  while (!some_exit_condition) {
    long long ll; 
    printf("Insert value for size : ");
    if (scanf("%lld", &ll) != 1) {
      puts("Numeric input missing");
      break;
    }
    if (ll < 0 || ll > SIZE_MAX) {
      puts("Size out of range");
      break;
    }

    sz = (size_t) ll;
    void *new_ptr = realloc(my_time, sz * sizeof *my_time);
    if (new_ptr == NULL && sz != 0) {
      puts("Out of memory");
      break;
    }
    my_time = new_ptr;

    // do something with `my_time` and `sz`

  }
  // Clean-up
  free(my_time);
  my_time = NULL;
  sz = 0;

  return 0;
}

关于c - 在 C 中动态增加数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32619428/

相关文章:

javascript - 如何在 Javascript 中对 Array map() 函数输出进行排序

arrays - 如何使用 'Divide and Conquer' 方法计算出现次数

c - 如何malloc 8*10^9 int 内存?

c++ - 两个不同大小的硬编码数组到一个二维 vector 中

c++ - 为什么在此代码中调用析构函数?

c - 在 C 中用变量初始化数组

c - libpng,c代码,如何将RGB值转换为像素值?

C - 将 argv[1] 附加到 unix PATH 的末尾

c - 二进制的无效操作数(有 float 和 float )

r - 错误: C stack usage 7969408 is too close to the limit when using fredr