访问内存冲突问题 [英] access memory violation problem
问题描述
大家好,
Hi everybody,
char *ptr="hello";
ptr[0]=''y'';
编译器引发访问冲突,请指导我做错了什么.
如果我按照下面的要求编写如下代码,则该代码按我的期望工作.
compiler raise access violation, please guide what i doing wrong.
if i write code like below it working as per my expectation.
char *ptr="Ranu";
char temp;
temp=ptr[1];
临时包含预期的"a".
等待回复.
致以问候
Narayan
temp contain "a" that is expected.
waiting for reply.
With Regards
Narayan
推荐答案
char * ptr ="hello";
ptr [0] =''y'';
编译器引发访问冲突
char *ptr="hello";
ptr[0]=''y'';
compiler raise access violation
:confused:我认为您的意思是您在运行时遇到访问冲突,而不是由于错误而导致编译失败.
"hello"是常量字符串文字.可以将其放置在设置为只读的内存中.
设置指向此不可更改的字符串的指针的正确方法是:
:confused: I think you mean that you get an access violation at runtime, not that the compile fails due to an error.
"hello" is a constant string literal. It may be placed in memory that is set up as read only.
The correct way to set up a pointer to this unalterable string is:
const char *ptr = "hello";
现在很明显,尝试更改它是错误的.出于历史原因,向后兼容的原因,允许您最初编写该表单的形式进行编译.正如您所发现的,它不能使常量在运行时可以安全地修改.
在第二种情况下,您正在读取常量-没问题,并且正在写入变量-也没有问题.
请注意,如果您想要常量字符串的非常量副本,则可以这样写:
Now it is clear that trying to change it is wrong. The form that you originally wrote it in is allowed to compile for historical, backwards compatibility reasons. It does not, as you have discovered, make the constant safely modifiable at runtime.
In your second case, you are reading from the constant - no problem, and writing to a variable - also no problem.
Note that if you want a non-const copy of the constant string, you could write:
char text[] = "hello";
text[0] = ''y'';
这样会创建一个足以容纳字符串的数组,并将字符串从其只读"位置复制到该数组.
This creates an array big enough to hold the string and copies the string to it from its "read-only" location to that array.
这篇关于访问内存冲突问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!