Reputation: 129
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.
Upvotes: 1
Views: 136
Reputation: 310920
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;
}
Upvotes: 2
Reputation: 403
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;
}
Upvotes: 0