Slain wrote:
> I am a beginner and have some confusion with respect to pointers and
> strings. It seems that the pointers with dealing with integer arrays
> behave differently, as opposed to strings. Can some one explain me the
> difference?
>
> Sample Program:
>
> int main()
> {
> int array[]={1,2,3,4,5};
> char array1[]={"Name is Max"};
>
> int *ptr;
> char *ptr1;
> ptr=array;
> ptr1=array1;
>
> cout<<"The array is "<<array<<endl;
array decays into a pointer to its first value. As cout has a way to output
const void* (== void const*), but not int*, the pointer is implicitly
converted to const void*.
> cout<<"ptr is "<<ptr<<endl;
Here, you already have an int*. It is converted to a const void* and
printed.
> cout<<"*ptr is "<<*ptr<<endl;
*ptr is an int, and cout has a << operator to print ints.
> cout<<"The array is "<<array1<<endl;
As with array, array1 also decays to a pointer to its first element. But
this time, the type is char*, and that can convert to a const char* (==
char const*), for which cout has a special output operator: It is treated
as a null terminated string.
> cout<<"ptr1 is "<<ptr1<<endl;
Will call the same operator as array1 did.
> cout<<"*ptr1 is "<<*ptr1<<endl;
And this uses the char output operator.
> }
> Output:
> The array is 0xbfe09380
> ptr is 0xbfe09380
> *ptr is 1
>
> The array is Name is Max
> ptr1 is Name is Max
> *ptr1 is N
>
>
> I can understand that in both the cases, *ptrx points to the element
> in it's address location. But why in the case of "ptr1", when I am
> using a string ptr1 refers to "Name is Max" and not the address of the
> "array1', like it did with "array".
Because the standard says const char* are to be treated specially by cout
and other ostream objects. In the same manner, wostream and wcout treat
const wchar_t* specially.
--
rbh
|