-1

I have this code:

void func(char *c){
    c = 'B';
    printf("s en func: %c\n", c);
}
int main()
{
    char *s = 'A';
    printf("s en main: %c\n", s);
    func(s);
    printf("s en main 2: %c\n", s);

    return 0;
}

I would like an output like this:

s en main: A

s en func: B

s en main 2: B

but i have this:

s en main: A

s en func: B

s en main 2: A

Why does this happen and how can I solve it?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
ted9090
  • 1
  • 1
  • 2
    I suggest that you [enable all compiler warnings](https://stackoverflow.com/q/57842756/12149471) and pay attention to them. I'm reasonably certain that your compiler would not accept your code without giving you a warning. – Andreas Wenzel Jul 31 '21 at 17:15

1 Answers1

2
char *s = 'A';

Your program is undefined as soon as you access *s, which you never did. You just used it as a character.

You seem to want

void func(char *c){
    *c = 'B';
    printf("s en func: %c\n", *c);
}
int main()
{
    char value = 'A';
    char *s = &value;
    printf("s en main: %c\n", *s);
    func(s);
    printf("s en main 2: %c\n", *s);

    return 0;
}

That is, filling in * everywhere to follow the pointer and declaring a variable to hold the initial 'A'.

Joshua
  • 40,822
  • 8
  • 72
  • 132