Can you define the size of an array at runtime in C

后端 未结 10 1287
走了就别回头了
走了就别回头了 2021-01-02 18:35

New to C, thanks a lot for help.

Is it possible to define an array in C without either specifying its size or initializing it.

For example, can I prompt a u

10条回答
  •  一个人的身影
    2021-01-02 19:00

    Perhaps something like this:

    #include 
    #include 
    
    /* An arbitrary starting size. 
       Should be close to what you expect to use, but not really that important */
    #define INIT_ARRAY_SIZE 8
    
    int array_size = INIT_ARRAY_SIZE;
    int array_index = 0;
    array = malloc(array_size * sizeof(int));
    
    void array_push(int value) {
      array[array_index] = value;
      array_index++;
      if(array_index >= array_size) {
        array_size *= 2;
        array = realloc(array, array_size * sizeof(int));
      }
    }
    
    int main(int argc, char *argv[]) {
      int shouldBreak = 0;
      int val;
      while (!shouldBreak) {
        scanf("%d", &val);
        shouldBreak = (val == 0);
        array_push(val);
      }
    }
    

    This will prompt for numbers and store them in a array, as you asked. It will terminated when passed given a 0.

    You create an accessor function array_push for adding to your array, you call realloc from with this function when you run out space. You double the amount of allocated space each time. At most you'll allocate double the memory you need, at worst you will call realloc log n times, where is n is final intended array size.

    You may also want to check for failure after calling malloc and realloc. I have not done this above.

提交回复
热议问题