I’m trying to pass in a memory reference to a character in a string and edit it in a function using C. The code is below:
void EditChar(char *input) {
printf("# %s #",*input);
*input = *input << 1
}
int main() {
char *string ="aaaa";
EditChar(&string[2]);
printf("%s",string);
}
I can print the character inside the function fine which I presume must mean it’s following the pointer so why am I unable to edit the pointer location of that character, any ideas?
The lack of a ; on line 3 is going to cause problems to start with.
You’re passing a character instead of a character pointer on line 2.
And on my mac, once you fix those problems, you get a bus error on line 3 because you’re trying to change read-only memory.
char *string =strdup(“aaaa”);
and now it works.
Also, as stated in question comments, instead of strdup, you may want to use
char string[] = “aaaa”;