Pointer to Arrays

I have created an Array of chars.

char name[10]={'p','h','o','n','e'};

then I used a pointer to hold the address of Array.

1
2
3
char name[10]={'p','h','o','n','e'};
char* ptrToName=name;
cout<<ptrToName<<endl<<endl; 


I know that name of Array is address of first element and so I expect it just to print address of first element. but it prints all of the elements in Array:

phone


I tried it with int data type and it just prints address of first element.

1
2
3
int num[10]={1,2,3,4,5};
int* ptrToNum=num;
cout<<ptrToNum<<endl;


Result:

0x22ff20


I am wondering if someone can tell me why they give me different answers. One of the pointers prints all of the elements and other one prints Address of first element.

All of the code is here:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
char name[10]={'p','h','o','n','e'};
char* ptrToName=name;
cout<<ptrToName<<endl<<endl;

int num[10]={1,2,3,4,5};
int* ptrToNum=num;
cout<<ptrToNum<<endl;

system("pause");
return 0;
}


It's because a char* is a Cstring, and so ostreams have a special overload for a char* that prints out the characters for you.
This happens because the << operator of the cout object is designed to behave differently for different types. The mechanism used to do that is called (operator) overloading. I guess you'll eventually learn about that.

The default behavior of cout-ing a char pointer is printing the entire string because that's what you almost always want to do with a char pointer. Of course, there are ways to get the address:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main()
{
    char name[10]={'p','h','o','n','e'};
    char* ptrToName=name;

    //printing the whole string
    cout << name << endl;
    cout << ptrToName << endl;

    //printing the address
    cout << (void*)&name[0] << endl;
    cout << (void*)ptrToName << endl;

    system("pause");
    return 0;
}

You might also have noticed that the char type is treated in a special way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
    char c=65;

    //printing the character
    cout << c << endl;

    //printing the ascii code
    cout << (int)c << endl;

    system("pause");
    return 0;
}
Last edited on
Topic archived. No new replies allowed.