DartmouthMan
DartmouthMan

Reputation: 1

An IF Statement Is Changing An Array Element In A Function

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

Upvotes: 0

Views: 50

Answers (1)

Luminaire
Luminaire

Reputation: 334

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

Upvotes: 2

Related Questions