Help me out, gurus
/*
* In this function, I want the static variable position to point to next element
* of the str, every time I call this function.
*/
void function(char *str){
static char *position = str;
/* Do something here to this position */
position += 1;
}
The purpose of this program is to do string substitution, every time I substituted a pattern of the str I have to let the static position variable point to a new position of the str, and then I will copy every thing into another new string.
The problem is, the compiler keep telling me “the initializer element is not a constant”, how can I fix this?
You can’t have a static variable in your function to point to the next element of
str, becausepositionis a global variable that is initialized once, andstrmay have different value every time you call a function.What you need here is a loop that iterates over
str,or have a loop outside this function and pass
strincremented by 1 every iteration.Of course, you can initialize a static to
NULLfirst and use it to check if you started iterating overstr, but that’s poor style: too stateful and error prone, not reentrant and not thread-safe.