Relation between pointer and arrays in C++

#include<iostream>
using namespace std;
int main()
{
int arr[]={1,2,3};
cout<<"Base Address of integer array:"<<arr;
char ar[]="abcd";
cout<<"\n";
cout<<"Base address of character array:"<<ar;
}

In case of integer arrays the array name will give you the base address of that array(Please refer line no.6, in the above program). But I don't understand why this is not working for character array.


Thanks in advance.
Last edited on
1
2
char ar[] = "abcd" ; i // string
cout<<"Base address of character array:"<< &ar << endl ;

Because ar[] is a string.
A string is an array of characters.

The ostream << operator is overloaded to recognize a pointer to char (char*) as a C-style string -- a null-terminated character array.

The ostream << operator is also overloaded to recognize a pointer to void (void*) and display the pointer's value (the address).

All other types are not guaranteed to work, IIRC. To get addresses, cast to (void*).
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
  {
  int  ia[] = { 1, 2, 3 };
  char ca[] = "abcd";

  cout << "Address of integer array: "   << (void*)ia << "\n";
  cout << "Address of character array: " << (void*)ca << "\n";

  return 0;
  }

Hope this helps.
Last edited on
Topic archived. No new replies allowed.