Why does the program,
char *s, *p, c;
s = "abc";
printf(" Element 1 pointed to by S is '%c'\n", *s);
printf(" Element 2 pointed to by S is '%c'\n", *s+1);
printf(" Element 3 pointed to by S is '%c'\n", *s+2);
printf(" Element 4 pointed to by S is '%c'\n", *s+3);
printf(" Element 5 pointed to by S is '%c'\n", s[3]);
printf(" Element 4 pointed to by S is '%c'\n", *s+4);
give the following results?
Element 1 pointed to by S is 'a'
Element 2 pointed to by S is 'b'
Element 3 pointed to by S is 'c'
Element 4 pointed to by S is 'd'
Element 5 pointed to by S is ' '
Element 4 pointed to by S is 'e'
How did the compiler continue the sequence? And why does s[3]
return an empty value?
Yes, you can apply the ++ increment operator to an object of type char , with the expected results in most cases: char c = 42; c++; printf("c = %d\n", c); // prints 43.
For example, incrementing a char pointer will increase its value by one because the very next valid char address is one byte from the current location. Incrementing an int pointer will increase its value by four because the next valid integer address is four bytes from the current location.
It doesn't continue the sequence. You are doing *s+3
which first dereferences s
to give you the char
with value 'a'
, and then you are adding on to that char
value. Adding 3 to 'a'
gives you the value of 'd'
(at least in your execution character set).
If you change them to *(s+1)
and so on, you'll get the undefined behaviour which is expected.
s[3]
accesses the last element of the string which is the null character.
Notice that *s
is a character, which is essentially a number. Adding another number to it, results in a character with a higher ASCII value.
The s[3]
is empty, because you only assigned "abc" to entries 0,1,2 respectively. In fact the 3rd character is the '\0' character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With