Initializing an array after declaration

前端 未结 4 1387
自闭症患者
自闭症患者 2021-01-27 01:56

gcc 4.4.3 c89

I have the following code as a sample of what I am trying to do. I don\'t know the actual size of the array, until I enter the function. However, I don\'t

4条回答
  •  太阳男子
    2021-01-27 02:25

    If you are using a global array then you need to know its size (or it's maximum size) at the time you declare it. E.g.

    char *devices_names[MAX_DEVICES];
    

    If you can't do this then you have no option but to use a pointer and dynamically allocated memory.

    E.g.

    char **devices_names = 0;
    
    void fill_devices(size_t num_devices)
    {
        devices_names = malloc( num_devices * sizeof *devices_names );
    
        /* ... */
    }
    

    Of course this has implications such as how do you prevent people accessing the array before it has been allocated and when do you free it?

提交回复
热议问题