Reputation: 482
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.
Upvotes: 1
Views: 78
Reputation: 36092
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.
Upvotes: 0
Reputation: 154035
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.
Upvotes: 3