开发者

address value of character pointers

//if the code is

char str[]="hello";    
char *s开发者_开发问答ptr=&str[2];  
cout<<sptr;  

//the output is not a hexadecimal value but llo

....why?

//also consider the following code

char array[]="hello world";  
char array1[11];  
int i=0;  
while(array[i]!='\0')  
{array1[i]=array[i];  
 i++;}

//if we print array1,it is printed as hello world, but it should have stopped when the space between hello and world is encountered.


The operator<< overload used by output streams is overloaded for const char* so that you can output string literals and C strings more naturally.

If you want to print the address, you can cast the pointer to const void*:

std::cout << static_cast<const void*>(sptr);

In your second problem, \0 is the null terminator character: it is used to terminate the string. array actually contains "hello world\0", so the loop doesn't stop until it reaches the end of the string. The character between hello and world is the space character (presumably): ' '.


  1. When you print a char*, it's printed as a string.

  2. '\0' is not ' '


Regarding your first question:

By default, a char is interpreted as its textual representation trough a call to std::cout.

If you want to output the hexadecimal representation of your character, use the following code:

std::cout << std::hex << static_cast<int>(c);

Where c is your character.

In your code:

cout<<sptr;

sptr is a pointer to a char, not a char so std::cout displays it as a C-string.

Regarding your second question:

A space is the ASCII character 32, not 0. Thus your test just checks for the ending null character for its copy.


With regards to cout, there is a special overload for writing const char * (and char *) to streams that will print the contents rather than the pointer.

With regards to array1, actually there is nothing wrong with making it size 11 as you do not copy the null byte into it. The issue comes though when you try printing it, as it will try to print until it finds a 0 byte and that means reading off the end of the array.

As it stands the compiler may well pad out a few bytes because the next thing that follows is an int so it is likely to align it. What is actually in that one byte of padding could be anything though, not necessarily a zero character.

The next few characters it is likely to meet will be the int itself, and depending on the endian-ness the zero byte will be either the first or second.

It is technically undefined behaviour though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜