简体   繁体   English

在C中动态增加数组大小

[英]Increasing array size dynamically in C

I need to increase length of 2 arrays according to user input. 我需要根据用户输入增加2个数组的长度。 I'm using the code below. 我正在使用下面的代码。 But output is not matching with user input. 但是输出与用户输入不匹配。

    #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;
    }

When user inputs the values: 当用户输入值时:

    35 4
    20 3
    40 1
    60 7
    20 8

Then this is the output: 然后是输出:

    8  4
    20 3
    40 1
    60 7
    20 8

If length of array exceeded 4, the last element of the time array will be printed as the first element of the size array. 如果数组的长度超过4,则time数组的最后一个元素将被打印为size数组的第一个元素。

Why does my program give this output? 为什么我的程序会给出此输出?

Something to get you started. 可以帮助您入门的东西。

Use realloc() to re-size the memory pointer to by a pointer. 使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM