• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 205
  • Last Modified:

Pointer to a character problem

Given the program below:

//**** begin
#include <iostream>
using namespace std;

void main()
{
     char data[] = {'a','b','c','d','\0'};
     char * b = data;
     cout << &data << endl << b << endl;
     cout << &b << endl << *b << endl;
}
//**** end

Why does it output the following?
//****
0012FF78
abcd
0012FF74
a
//****

I had expected "cout << b" to print out the memory address contained in b, but rather it prints out the characters in the array.  I think that "cout << &data" will print the address of the first character, but "cout << &data[1]" will print out "bcd" instead of a memory address.  

Does it have to do with the fact that the pointer is passed to cout, which is taking the array by reference or something? (Not sure if this question makes any sense, sorry.)

I'd really appreciate any help someone can give me in understanding the matter. Thanks in advance.

0
hamsterboy143
Asked:
hamsterboy143
1 Solution
 
ExceterCommented:
>> I had expected "cout << b" to print out the memory address contained in b, but rather it prints out the characters in the array.

No, b is a pointer, as is data, cout either will print out the data contained at the memory address they point to. To print out the address you would have to say,

cout << *b;

>> I think that "cout << &data" will print the address of the first character

That is correct. All other array locations are reached via an offset or index.

>> cout << &data[1]" will print out "bcd" instead of a memory address.  

That is because cout start reading data at the address of data plus the index. So it skips the 'a' at the beginning of the array.

Exceter
0
 
bcladdCommented:
Pointers to char are special. That is how C stores strings (as you stored the null-terminated batch of characters in data). Thus when passing a char * to cout, it assumes you are trying to print a C-style string.

You can prove this to your self by changing the content type to int.

-bcl
0
 
PlanetCppCommented:
>>To print out the address you would have to say,

>>cout << *b;
*b would print out 'a' (in the case that 'a' is first char)
&b prints the address of b
>>>> I think that "cout << &data" will print the address of the first character

>>That is correct. All other array locations are reached via an offset or index.

cout<<&data prints the address of the array or the address of where 'a' is.
the offset can be reached by
cout<<*(b+1)  or 'b' in this case
0
 
vinay_krishnaCommented:
Bsladd is right.

there is one advantage of using pointer to char as it acn be reassigned to differnt chars.
 
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now