0

I have a struct of words:

typedef struct {
   char *word;
   unsigned long occurrences;
} Word;

and I want to malloc an array of these but I don't know how large the size will be. Is there a way to malloc an array of structs without knowing the size of the array beforehand?

Thanks.

2
  • 3
    heh? if you don't know the size, what's the point of allocating memory? Commented Apr 21, 2016 at 17:31
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. Commented Apr 21, 2016 at 17:31

1 Answer 1

3

You can allocate memory with malloc(), and then change size with realloc()

typedef struct {
 char *word;
 unsigned long occurrences;
} Word;

int main()
{
  Word *arr = malloc(sizeof(Word) * n);
  // do smth
  // need more
  arr = realloc(arr, sizeof(Word) * more);

  return 0;
}
Sign up to request clarification or add additional context in comments.

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.