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

后端 未结 10 1204
走了就别回头了
走了就别回头了 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 18:57

    Well, you can dynamically allocate the size:

    #include 
    
    int main(int argc, char *argv[])
    {
      int *array;
      int cnt;
      int i;
    
      /* In the real world, you should do a lot more error checking than this */
      printf("enter the amount\n");
      scanf("%d", &cnt);
    
      array = malloc(cnt * sizeof(int));
    
      /* do stuff with it */
      for(i=0; i < cnt; i++)
        array[i] = 10*i;
    
      for(i=0; i < cnt; i++)
        printf("array[%d] = %d\n", i, array[i]);
    
      free(array);
    
      return 0;
    }
    

提交回复
热议问题