0

When my program runs, the IF ( ch[0] == 'P') actually puts the value 'P' into ch[0]. Any ideas what is happening here? The output is: "Array is Pyz"

char *try1(char ch[]);

int main()
{
  char ch[] = { 'x','y','z' }, *ch1;
  ch1=try1(ch); 
  printf("\nArray is %s\n",ch1);
  return 0;
}

char *try1 (char ch[])
{
  if (ch[0]=='P')
  {
    ch[1]='Q';
  }

  return ch;
}
5
  • 3
    Are you sure you have a == and not a =? Commented Dec 2, 2016 at 2:57
  • Thank you BJ Myers. You are right. Sorry, I'd tried to be very careful before I posted this but I missed that. I'll be more thorough in the future. Commented Dec 2, 2016 at 3:01
  • You should look into proper C formatting. Or learn how to thoroughly obfuscate your code. Commented Dec 2, 2016 at 6:10
  • A strong case for always placing the literal on the left side of an equality expression, so the compiler catches the problem rather than you having to spend your time and effort debugging the program. Commented Dec 2, 2016 at 7:47
  • the array ch[] is not NUL terminated, so the call to printf() will result in garbage being output after the actual 3 bytes in the array until a NUL byte is encountered. This is undefined behavior and can lead to a seg fault event. Commented Dec 2, 2016 at 7:51

1 Answer 1

2

If you want to interpret ch as a string, you should terminate the array with '/0'. Replace

char ch[] = { 'x','y','z'}

with

char ch[] = { 'x','y','z', '\0' }

and the output becomes "Array is xyz."

For more information, read https://en.wikipedia.org/wiki/Null-terminated_string

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.