简体   繁体   中英

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.

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 */
    free(pData);
    free(pData2);
    ...
}

First of all, try to make sense of the requirement. You cannot possibly initialize a memory of "unknown" size, you can only have it initialized once you have a certain amount of memory (in terms of bytes). So, the first thing is to get the memory allocated.

This is the scenario to use memory allocator functions, malloc() and family, which allows you to allocate memory of a given size at run-time. Define a pointer, then, at run-time, get the memory size and use the allocator functions to allocate the memory of required size.

That said,

  • calloc() initializes the returned memory to 0 .
  • realloc() is used to re-size the memory at run-time.
  • Also, while using dynamic memory allocation, you should be careful enought to clean up the allocated memory using free() when you're done using the memory to avoid memory leaks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM