如何更改char *name ='speremple'supple; quot';带有char *名称
我正在研究C ++,以了解记忆。
char *name = "example";
*(&name+1) = (char*)'A';
std::cout << name << std::endl;
正在返回示例不是 ea pample 。
我的想法是获取“ x”的内存地址并将其更改。
不是const,所以我应该能够更改地址的价值正确吗?
观察:我知道它如何以其他方式,我很好奇这样做。
I am studying c++ to get a good understanding of memory.
char *name = "example";
*(&name+1) = (char*)'A';
std::cout << name << std::endl;
is returning example not eAample.
My idea is to get the memory address of 'x' and changed it.
Is not a const so I should be able to change the value of the address right?
obs: I know how do it in other ways, I am curious to make this way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该声明
无效。
在C ++字符串中具有常数字符数组的类型。这意味着您必须写作
,并且您可能不会更改字符串字面。
即使在字符串文字具有非恒定字符阵列类型的C中,您也可能不会更改字符串文字。任何更改字符串字面的尝试都会导致不确定的行为。
此表达式
指向指针名称之外。因此,请说明指针表达式
*(&amp; name+1)
调用未定义的行为。此外,此表达式
(char*)'a'
没有意义。它表示您正在尝试使用字符“ A”代码的值(例如,ASCII等于65)作为内存的地址。您可以做的是以下内容
,或者如果您想处理指针表达式,那么
您可以
在这里写的是一个基于您的想法的演示程序。第一个基于范围的循环将由支持C ++ 20的编译器编译。否则,您可以像
这里一样重写它。
程序输出是
This declaration
is invalid.
In C++ string literals have types of constant character arrays. It means that you have to write
and you may not change the string literal.
Even in C where string literals have types of non-constant character arrays you may not change a string literal. Any attempt to change a string literal results in undefined behavior.
This expression
points outside the pointer name. So dereferencing the pointer expression
*(&name+1)
invokes undefined behavior.Also this expression
(char*)'A'
does not make a sense. It denotes that you are trying to use the value of the code of the character 'A' (that for example in ASCII is equal to 65) as an address of memory.What you could do is the following
Or if you want to deal with pointer expressions then instead of
you could write
Here is a demonstration program that is based on your idea. The first range-based for loop will be compiled by a compiler that supports C++ 20. Otherwise you can rewrite it like
Here you are.
The program output is