Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing char pointers in C++

Tags:

c++

char

pointers

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?

like image 334
zalyahya Avatar asked May 11 '13 14:05

zalyahya


People also ask

Can you increment a char pointer in C?

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.

Can you increment a char pointer?

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.


2 Answers

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.

like image 154
Joseph Mansfield Avatar answered Oct 11 '22 13:10

Joseph Mansfield


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.

like image 22
chtenb Avatar answered Oct 11 '22 11:10

chtenb