How to create an array without declaring the size in C?

后端 未结 3 1488
盖世英雄少女心
盖世英雄少女心 2020-12-29 11:55

I\'m pretty new to new C and I wasn\'t able to find anything related to this (maybe because I\'m not really sure what I\'m looking for).

I\'m trying to create a int

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 12:31

    You don't declare an array without a size, instead you declare a pointer to a number of records.

    so, if you wanted to do

    int bills[];
    

    The proper way to do this in C is

    int* bills;
    

    And you will have to allocate the size at some point in time and initialzie the array.

    bills = (int*)malloc(sizeof(int)*items);
    

    The same goes for arrays of other data types. If you don't know the size of the array until runtime, you should use pointers to memory that is allocated to the correct size at runtime.

提交回复
热议问题