Home > Enterprise >  variable should not reset when calling the function again?
variable should not reset when calling the function again?

Time:07-06

I want the value of a pointer variable to be initialized to NULL at the start of the execution. This variable is used in a function and its value may also get changed within the function. But I do not want the value of this variable to reset to NULL whenever a function call is made. Instead, its value should be equal to the updated value from its previous function call. Cannot use global variables.

void function(struct node *variable) {
  // changes value of pointer variable to something else
  variable = something;
}

void another_function(void) {
  // have to be initialised before passing in as argument or else will raise error
  struct node *variable = NULL;

  function(variable);
}

// then calling this function multiple times in main
another_function();
another_function();

help would be much appreciated.

CodePudding user response:

Firstly, the pointer variable variable is local to another_function. It does not live outside of this scope.

Secondly, when you pass it to function, the variable parameter of that function is also local to that function. You immediately assign a value to that local variable, but that doesn't change the variable you passed in.

CodePudding user response:

You can use the static keyword when declaring your initial pointer variable. It will only be initialized when first encountered during the execution.

But as for now, your code will probably not do what you intend it to do. The pointer variable in function is local and will have no effect on the value of variable in another_function. You should use a pointer of pointer for this effect.

  • Related