1

Firstly, Sorry about my bad english. I wanna ask something that I expect amazing. I'm not sure this is amazing for everyone, but It is for me :) Let me give example code

char Text[9] = "Sandrine";
for(char *Ptr = Text; *Ptr != '\0'; ++Ptr)
cout << Ptr << endl;

This code prints

Sandrine
andrine
ndrine
drine
rine
ine
ne
e

I know it's a complicated issue in C++. Why İf I call Ptr to print out screen it prints all of array. However if Text array is a dynamic array, Ptr prints only first case of dynamic array(Text). Why do it happen? Please explain C++ array that how it goes for combination of pointing array.

thanks for helping.

7
  • Because there's a special output handler for const char *. Commented Nov 9, 2013 at 22:58
  • could you specify what kind of dynamic array you mean? Commented Nov 9, 2013 at 23:00
  • @KillianDS e.g char* myarray = new char("play"); Commented Nov 9, 2013 at 23:01
  • @chris did you mean that Text is const char that point all of arrays elements? Commented Nov 9, 2013 at 23:01
  • 1
    new char("play") doesn't create an array! Instead, it should fail to compile: there is no way to construct a char from a char const*. Commented Nov 9, 2013 at 23:06

2 Answers 2

3

There is nothing particular special about arrays here. Instead, the special behavior is for char const*: in C, pointers to a sequence of characters with a terminating null characters are used to represent strings. C++ inherited this notion of strings in the form of string literals. To support output of these strings, the output operator for char const* interprets a pointer to a char to be actually a pointer to the start of a string and prints the sequence up to the first null character.

Sign up to request clarification or add additional context in comments.

Comments

0

When you write

char Text[9] = "Sandrine";

the "Text" is an address in memory, it is the starting address of your string and in its first location there is a 'S' followed by the rest of the characters. A string in C is delimited by a \0 i.e. "S a n d r i n e \0"

When you write

for(char *Ptr = Text; *Ptr != '\0'; ++Ptr)
  cout << Ptr << endl;

when the for loop runs the first time it prints the whole string because Ptr points to the start of the string char* Ptr = Text when you increment Ptr you are pointing to the next character Text + 1 i.e. 'a' and so on once Ptr finds \0 the for loop quits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.