Dent7777 Dent7777 - 1 year ago 60
C Question

C: How do I initialize a global array when size is not known until runtime?

I am writing some code in C (not C99) and I think I have a need for several global arrays. I am taking in data from several text files I don't yet know the size of, and I need to store these values and have them available in several different methods. I already have written code for reading the text files into an array, but if an array isn't the best choice I am sure I could rewrite it.

If you had encountered this situation, what would you do? I don't necessarily need code examples, just ideas.

Answer Source

Use dynamic allocation:

int* pData;
char* pData2;

int main() {
    pData = malloc(count * sizeof *pData); // uninitialized
    pData2 = calloc(count, sizeof *pData2); // zero-initialized
    /* work on your arrays */