3

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 think I can set the array size after I have declared it. I need it global as some other functions will need to access the device names.

Many thanks for any suggestions,

/* global */
char *devices_names[];

void fill_devices(size_t num_devices)
{
    devices_names[num_devices];

    /* start filling */
}
0

4 Answers 4

3

You'll need to allocate the memory dynamically using malloc:

char **device_names;

void fill_devices(size_t num_devices)
{
    device_names = malloc(num_devices * sizeof(char*));
}

And then use free(device_names); to free the memory when you no longer need it.

Sign up to request clarification or add additional context in comments.

1 Comment

Apologies, sepp2k. I accidentally edited your answer instead of mine.
3

Make it dynamic:

char **g_device_names;
int g_num_devices;

void fill_devices(size_t num_devices) {
    g_device_names = malloc(sizeof(char*) * num_devices);
    g_num_devices = num_devices;
    ...
}

Comments

3

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?

Comments

2

You should use a pointer, so when you enter the method the array is still not declared. You can use malloc to set the correct size. Look at this article: arrays and malloc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.