指针和字符串文字 [英] pointers and string literals

查看:139
本文介绍了指针和字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多次我看到以下语句:

Many a times I have seen the following statements:

char* ch = "Hello"
cout<<ch;

我得到的输出是 Hello 。我知道ch指向字符串Hello的第一个字符,Hello是一个字符串字面量并存储在只读存储器中。因为,ch将第一个字符的地址存储在字符串文字中,因此不应该使用语句

The output I get is "Hello". I know that ch points to the first character of the string "Hello" and that "Hello" is a string literal and stored in read only memory. Since, ch stores the address of the first character in the string literal, so shouldn't the statement,

cout<<ch;

给出输出字符地址,一个指针变量?相反,它打印字符串字面量本身。
此外,如果我写这个,

give the output "the address of a character" because, it is a pointer variable? Instead it prints the string literal itself. Moreover, if I write this,

ch++;
cout<<ch;

它提供输出 ello 。类似地,它也发生在更多的连续的ch ++语句。


可以有人告诉我,为什么会发生?

Btw,我已经看到了与字符串字面量有关的其他问题,但是所有这些都解决了为什么我们不能做类似* ch ='a'的事情?

EDIT:我也想参考这个如果我键入,C也会发生,

It gives the output, "ello". And similarly, it happens with more consecutive ch++ statements too.

can anybody tell me, why does it happen?
Btw, I have seen other questions related to string literals, but all of them address the issue of "Why can't we do something like *ch='a'?
EDIT : I also want to ask this in reference to C, it happens in C too, if I type,

printf("%s",ch);

为什么?

推荐答案

运算符的重载版本

ostream& operator<< (ostream& , const char* );

char *p = "Hello";
cout << p;

这个重载定义了如何打印字符串而不是打印地址。但是,如果要打印地址,使用,

This overload defines how to print that string rather than print the address. However, if you want to print the address, you can use,

cout << (void*) p;

,因为这将调用另一个重载,只打印地址流: -

as this would call another overload which just prints the address to stream:-

ostream& operator<< (ostream& , void* );

这篇关于指针和字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆