Home > Software engineering >  Changing a const char with a void function
Changing a const char with a void function

Time:10-05

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;
} 

CodePudding user response:

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;
} 
  • Related