zalyahya
zalyahya

Reputation: 153

Incrementing char pointers in C++

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?

Upvotes: 5

Views: 4543

Answers (2)

chtenb
chtenb

Reputation: 16184

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.

Upvotes: 2

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

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.

Upvotes: 9

Related Questions