Can you define the size of an array at runtime in

2020-02-28 19:15发布

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 user to enter numbers and store them in an int array ? I won't know how many numbers they will enter beforehand.

The only way I can think of now is to define a max size, which is not an ideal solution...

10条回答
混吃等死
2楼-- · 2020-02-28 19:39

If all you need is a data structure where in you can change its size dynamically then the best option you can go for is a linked list. You can add data to the list dynamically allocating memory for it and this would be much easier!!

查看更多
The star\"
3楼-- · 2020-02-28 19:39

Yes, absolutely. C99 introduced the VLA or Variable Length Array. Some simple code would be like such:

#include <stdio.h>

int main (void) {

    int arraysize;
    printf("How bid do you want your array to be?\n");
    scanf("%d",&arraysize);
    int ar[arraysize];  
    return 0;
}
查看更多
仙女界的扛把子
4楼-- · 2020-02-28 19:40

For something like this, you might want to look into data structures such as: Linked Lists (Ideal for this situation) Various Trees (Binary Trees, Heaps, etc) Stacks & Queues

But as for instantiating a variable sized array, this isn't really possible.

The closest to a dynamic array is by using malloc and it's associated commands (delete, realloc, etc).

But in this situation, using commands like malloc may result in the need to expand the array, an expensive operation where you initialize another array and then copy the old array into that. Lists, and other datatypes, are generally much better at resizing.

查看更多
对你真心纯属浪费
5楼-- · 2020-02-28 19:40

If you're looking for array facilities and don't want to roll your own, try the following:

  1. Glib
  2. Apache APR
  3. NSPR
查看更多
登录 后发表回答