What happens here is the following:
- in the function
main
you call printString
with a pointer to the string "hello"
- the
printString
function attempts to read a character with getchar()
- and save that character in the place of the 'h'
The rules of the language say that attempting to change that 'h' is Undefined Behaviour. If you're lucky, your program crashes; if you're very unlucky it will appear the program works.
In short: getchar()
is used for reading; putchar()
is used for writing.
And you want to write 5 letter: 'h', 'e', 'l', 'o', and another 'o'.
hello
^ ch is a pointer
ch *ch is 'h' -- ch points to an 'h'
Is there something after that last 'o'? There is! A '\0'
. The zero byte terminates the string. So try this (with printString("hello");
) ...
void printString(char *ch)
{
putchar(*ch); /* print 'h' */
ch = ch + 1; /* point to the next letter. */
/* Note we're changing the pointer, */
/* not what it points to: ch now points to the 'e' */
putchar(*ch); /* print 'e' */
ch = ch + 1; /* point to the next letter. */
putchar(*ch); /* print 'l' */
ch = ch + 1; /* point to the next letter. */
putchar(*ch); /* print 'l' */
ch = ch + 1; /* point to the next letter. */
putchar(*ch); /* print 'o' */
ch = ch + 1; /* point to the next letter. What next letter? The '\0'! */
}
Or you can write that in a loop (and call from main with different arguments) ...
void printString(char *ch)
{
while (*ch != '\0')
{
putchar(*ch); /* print letter */
ch = ch + 1; /* point to the next letter. */
}
}