First post! Hoping you can help as I'm really confused!
In the following code:
int main ()
{
int* NumberArray = new int [5];
int a = 0;
for (int i=0; i<5; i++)
{
NumberArray[i] = a;
a++;
}
cout << *NumberArray << ".\n";
char* theWord = new char [5];
theWord = "butt.";
cout << theWord << "\n"; // prints the word
cout << NumberArray << ".\n"; // prints pointer address
system ("pause");
return 0;
}
I am trying to work out why "cout << theWord" will print the entire array of characters, whereas "cout << NumberArray" will only print out the address of the first int in the array?...
I understand how the printing of the address is correct, but can't then work out why the address of the first character wouldn't be printed out?? To me it makes no sense that the whole set of characters is printed out instead.
Coder777: So when <iostream> sees there is a char* being passed into one of it's functions, it essentially knows that a word(s) is being passed in, and acts accordingly?
Essentially, it has within it's code a specific '<<' operator dealing with char*?
So when <iostream> sees there is a char* being passed into one of it's functions, it essentially knows that a word(s) is being passed in, and acts accordingly?
Last point!... I take it will there also be a similar '=' overloaded operator for allocating the full word to the char* pointer (making theWord = "butt."; possible without the need for a for loop? Would this also be contained within the stream class?
Last point!... I take it will there also be a similar '=' overloaded operator for allocating the full word to the char* pointer (making theWord = "butt."; possible without the need for a for loop? Would this also be contained within the stream class?
No, that has nothing to do with streams.
The assignment operator can be overload only within class (not for the build in types, so called POD (plain old data)). Since 'theWord' is a pointer to char theWord = "butt." only sets the pointer. That means the previously allocated memory (char* theWord = newchar [5];) is lost!
You need strcpy() in order to copy the string to the allocated memory. Be aware that a string like "butt." contains 6 char because of the the trailing 0 char.