OldSchool
OldSchool

Reputation: 2183

How to allocate static storage dynamically in c?

In a recursive method to group the external nodes of a tree, i need to allocate memory dynamically inside that function.But the statement

static node* ext_node = malloc (sizeof(node)); 

is not working, and compiler gives error,which says

initializer element is not constant.

In short i want to ask that how can i use the static keyword with a pointer in a recursive call when the memory to which the pointer is pointing is dynamically acquired?

I require this because, when it is required to add more element in the list, the method insert_to_end (node*) will take the responsibility of allocating the storage for new node, so with this i can create list of any length and that is too with exact memory requirement.

But how to achieve this in c language?

Upvotes: 1

Views: 121

Answers (2)

Sam Protsenko
Sam Protsenko

Reputation: 14743

If you really need to do so, just split it into 2 operations, like this:

static node *ext_node;

if (ext_node == NULL)
    ext_node = malloc(sizeof(node));

But it looks like flawed design for me (usually using static variables inside functions is a bad practice -- makes function not reentrable).

Why don't pass this ext_node to your function, as a parameter? And why are you need to do this variable static in the first place?

Upvotes: 3

Employed Russian
Employed Russian

Reputation: 213576

Note that in general using static in a recursive function is a mistake (and is also thread-unsafe). It is almost always better to pass required data into the function via parameters.

However, if you insist, you can do it this way:

static node* ext_node;
if (ext_node == NULL) ext_node = malloc (sizeof(node)); 

That error doesn't make sense

A C compiler will initialize static variables at compile time (this requirement was relaxed in C++, and your original code will compile with a C++ compiler).

You can do this:

static int foo;  // default initialized to 0
static int bar = 42;

but not this:

static int baz = some_func();  // Error: at compile time the value to put into baz is not known.

Upvotes: 5

Related Questions