0

If I had a structure like this

typedef struct {
        char word[101];
        int freq;
        char filename[100];
} WordArray;

and declared this inside a method instead of it being a global variable(so its local)

WordArray words[10000];

then how would I allocate memory to this?

I've had this

for (i=0;i<10000;i++)
        {
                 words[i] = (*WordArray)malloc(sizeof(WordArray));

        }

And fooled around with it but, got nothin. Suggestions?

3
Contributors
4
Replies
6
Views
5 Years
Discussion Span
Last Post by histrungalot
1

You already did by the declaration of WordArray words[10000]; The is allocated off the stack and you don't have to do anything. If you did: WordArray *words[10000], then you would have to allocate memory with a for loop like you have above. That is because its an array of pointers to WordArrays.

for (i=0;i<10000;i++)
{
      words[i] = (WordArray *)malloc(sizeof(WordArray));

}

Just realize that 10,000 WordArrays is 2.050 MBytes of memory and depending on you setup your stack may or may not be that large, for me my default stack size is 8 MBytes. For something that big you want to allocate that off of the heap (malloc).

0

Well, yeah thats what I had before, but I was told by my instructor to do it this way, hence I'm stuck with that declaration.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.