4

I want to declare a root node and have done the following.

typedef struct node
{
    bool is_word;
    struct node *children[MAX];

}node;

node *root = malloc(27 * sizeof(struct node));

When I try to compile, I get the following error:

dictionary.c:20:14: error: initializer element is not a compile-time constant
node *root = malloc(27 * sizeof(struct node));

What am I doing wrong?

Thanks in advance for your help.

11

It looks like you are trying to create and allocate memory for root outside of main or any other function call. This is not allowed. There are certain actions you can do outside of main. These all have to be things that can be coded at compile time. For instance, you can declare a global var outside of main. However, you can't do things outside of main or a function that must be done at run time, like assigning values to variables or allocating memory with malloc.

In this case, you want to declare root outside of main, node* root; and then, later, and inside of main, do the allocation there, root = malloc(...);

You had the right idea, but you need to do it in two steps.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

4
  • The thing is, supposedly we are not supposed to alter speller.c, where the main() function is located. As such, where should we put it? – chilliefiber Aug 26 '17 at 21:37
  • You are correct that speller is not to be altered. So why not do it where it's first needed, like in the beginning of load? – Cliff B Aug 26 '17 at 21:40
  • Ok, that's where I put it as well, but I think it's a very ugly solution. Don't you? – chilliefiber Aug 26 '17 at 21:48
  • Just the opposite. root is first used in load, so it makes the most sense to initialize it where it is first used. If the initialization needs to be changed because the code needs to be updated in the future, it's right where it needs to be and whoever is making the changes doesn't have to go hunting for it. In other words, this is considered best practice. If this were a local variable, it would be initialized when it is created or shortly after. With globals, it's only a little different because of the requirements of creating a global. – Cliff B Aug 26 '17 at 22:25
2

Just to add to this, I don't think you need root to be the size of 27 nodes, just the size of one node. Moreover, each level of the trie ought to have space for 27 characters, more than that is a waste of resources, so unless MAX is a #define for 27, then reconsider the use size of your pointer arrays.

1
  • Thanks! You are right! – Salamit Apr 14 '17 at 7:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .