Search code examples
cfunctioncharvoid

Changing a const char with a void function


I'm trying to understand the following code and how functions, void and char work together. I was wondering if it was possible to change the char output from 'a' to char 'b', with just editing the void function? I have tried void foo(char *x) { *x = 'b';}, however I receive an error saying 'core dumped', which I am confused about.

If it is impossible to change the const char ch = 'a'; value, how would you change the value of char ch = 'a' ?

Thank you~

#include <stdio.h>

void foo(char x) {
  x = 'b';
}

int main() {
  const char ch = 'a';
  foo(ch);
  printf("ch = %c", ch);
  return 0;
} 

Solution

  • No, it's not possible to do this only by changing the function. You need to change the function to take a pointer, change the caller to pass the address of the variable, and change the variable to non-const.

    #include <stdio.h>
    
    void foo(char *x) {
      *x = 'b';
    }
    
    int main() {
      char ch = 'a';
      foo(&ch);
      printf("ch = %c", ch);
      return 0;
    }