1

I'd like to save an input to a function and manipulate it across multiple calls. However, if I do the following...

int testFunc(char *toString) {
        static char *toChange = toString;
        static int counter = 0;

        toChange[counter] = 'A';
        printf("String is being corrupted... %s\n", toChange);
        counter++;

        return 0;
}

I get an error saying that the input toChange cannot be set to a non-static variable. I have been trying to figure out how to get around this but I cannot find any answers.

1
  • 1
    You should initiate your pointer to NULL, so, in the first call, you copy the string to your local variable, then, after that, you do not change its content anymore. Commented Oct 16, 2019 at 21:00

2 Answers 2

2

Static variables shall be initialized by constant expressions.

Write instead something like

 int testFunc(char *toString) {
    static char *toChange;
    static int counter;

    if ( toChange == NULL || toString == NULL ) 
    {
        toChange = toString;
        counter = 0;
    } 

    toChange[counter] = 'A';
    printf("String is being corrupted... %s\n", toChange);
    counter++;

    return 0;

}

Sign up to request clarification or add additional context in comments.

3 Comments

It would be even better to explicitly initialize toChange to NULL! But I think this will be the default, anyway (static data default to zero, I think?)
I am not sure if every compiler initializes local variables to zero. I recommend you never count on that.
@EduardoFernandes It is not just a local variable it is also a static variable and static variables are initialized by the compiler.
0

Do this:

int testFunc(char *toString) {
    static char *toChange = NULL;
    static int counter = 0;
    if (toChange == NULL) {
        toChange = (char*)malloc(strlen(toString) + 1);
        memset(toChange, 0, strlen(toString) + 1);
        strcpy(toChange, toString);
    }
    toChange[counter] = 'A';
    printf("String is being corrupted... %s\n", toChange);
    counter++;
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.