3

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.

3
  • 1
    Sorry... but how does it make sense? Commented Nov 12, 2016 at 18:07
  • @SouravGhosh Do you have anything you would like clarified? Commented Nov 12, 2016 at 18:41
  • I think i myself explained that in first paragraph of my answer. Commented Nov 12, 2016 at 18:43

2 Answers 2

6

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);
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

You forgot to test against failure (of malloc & calloc)
@BasileStarynkevitch: This is an example of how to address the problem. It is not full fledged, working ready-for-production code.
5

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.

1 Comment

There ought to be a crealloc because realloc does not zero the extra memory. It is more properly paired with malloc.

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.