Task of static variable C

Help me guru

/*
 * 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 perform line substitution, every time I replace the str template, I have to let the static position variable point to the new str position, and then I will copy each thing to another new line.

The problem is that the compiler keeps telling me that the “initializer element is not constant”, how can I fix this?

+3
source share
6 answers

, str, position - , , str , .

, str,

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

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);
    }
}

, NULL , , str, : , .

+9

, - , , reset 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;
   }
 }

, str NULL, , , , NULL, , .

+7

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';
 }

, :

while (more) {
   // do something
   more = function(string);
}
+5
static char *position = str;

, position , . ,

#include <stdio.h>
int j = 9;
static int k = j + 3; /* Error */
int main(){}

j str , .

+1

, static - . :

C ( static) . , .

++ , , , , . . , ; static , , .

+1
void func1();

char str[10] = "good";

int main()
{
   func1();
   return 0;    
}

void func1()
{
   static char *pos = &str[0];

   pos++;

   (pos) ? printf("%s\n",pos) : 0;  
}

. ReadWrite, . "ood", print "od"...

+1

Source: https://habr.com/ru/post/1764434/


All Articles