C静态变量问题

Rn2*_*2dy 3 c

帮帮我,大师

/*
 * 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;
 }
Run Code Online (Sandbox Code Playgroud)

这个程序的目的是进行字符串替换,每次我替换str的模式时我必须让静态位置变量指向str的新位置,然后我将每个东西复制到另一个新的字符串中.

问题是,编译器一直告诉我"初始化元素不是常量",我该如何解决这个问题?

Ale*_*x B 9

函数中不能有一个静态变量指向下一个元素str,因为它position是一个初始化一次的全局变量,str每次调用一个函数时都可能有不同的值.

你需要的是一个迭代的循环str,

void func1(char *str) {
    char *p;
    for (p = str; /* some condition here */; ++p) {
        /* Do something here to this position */
    }
}
Run Code Online (Sandbox Code Playgroud)

或者在此函数外部有一个循环,并且str每次迭代都会递增1.

void func1(char *str) {
    /* Do something here to this position */
}

void func2() {
    char *str = ...;
    ...
    char *p;
    for (p = str; /* some condition here */; ++p) {
        func1(p);
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以将静态初始化为NULL第一个并使用它来检查您是否开始迭代str,但这样的风格很差:太有状态且容易出错,不可重入且不是线程安全的.


Nat*_*man 7

你需要做的是找到一些方法来决定你是否在字符串的开头,在这种情况下你重置position或不重置,在这种情况下你增加它:

/*
 * 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;

   if (str) {
       position = str;
   } else {
       /* Do something here to this position */
       position += 1;
   }
 }
Run Code Online (Sandbox Code Playgroud)

现在,当strNULL,函数假定你继续使用与以前相同的字符串来工作,当它不为空,它假定你有一个新的字符串工作.


Dip*_*ick 5

这不是C的做事方式 - 它不是重新开始的 - 但如果你绝对必须:

/*
 * In this function, I want the static variable position to point to next element
 * of the str, every time I call this function.
 */
bool function(char *str){

   static char *last_str;
   static char *position;

   if (str != last_str)
       last_str = position = str;

   /* Do something here to this position */

   if (*position != '\0')
       ++position;
   else
       last_str = NULL;

   return *position != '\0';
 }
Run Code Online (Sandbox Code Playgroud)

然后你可以做以下事情:

while (more) {
   // do something
   more = function(string);
}
Run Code Online (Sandbox Code Playgroud)