what does (int *) animal tell us? Is it done correctly? |
Let's look at the similar line after that first, since that's easier to understand and explain.
(int*)ps
ps is a pointer to a char, as you know.
The thing is... when you give a char pointer to cout... it treats it special... like a string. Therefore when you say
cout << ps;
it will not print the pointer, but instead will go to whatever address you gave it and will print characters from that address until it finds a null. Effectively, it will print the string data pointed to by the pointer.\
But that is the special case. If you give cout
any other kind of pointer, it will not do that, and instead will just print the pointer as an address.
By doing
(int*)ps
we are casting ps from a char pointer to an int pointer. This "tricks" cout so that it will no longer print the string data... but instead will print the actual address that the pointer contains.
(int*)animal
is similar, but also has an implicit cast from an array name to a pointer. You can think of it as doing the same thing.
new char[strlen(animal) + 1] means that whatever size is taken for animal (say 4 bits) new char will allot 5 bits in memory? |
strlen follows whatever pointer you gives it and counts the number of characters it finds until it reaches the null terminator. It effectively gives you the length of the string.
Since animal contains "bear" -- which is 4 characters long -- strlen will return 4... giving you the length of the string.
Note the length is in
characters.. not in bits.
new char[x]
will create 'x' characters. In this case... since
strlen(animal)
gives us 4, and we are adding 1 to that...
ps = new char[strlen(animal) + 1];
<- this will allocate 5 characters with new[], and will assign a pointer to those 5 characters to our 'ps' pointer.
2) in strcpy(ps, animal) the address of animal is stored in ps? |
strcpy follows the 2nd pointer you give it (in this case, 'animal') and copies characters one by one to the 1st pointer (in this case, 'ps') until the null is found. It effectively copies the string data from one array to another.