简单代码的访问冲突错误 [英] Access violation error for a simple code

查看:64
本文介绍了简单代码的访问冲突错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我遇到以下情况.对于您来说,这可能是最简单的解决方案,但是如果您能在这方面帮助我,我将不胜感激.


Hi,

I came across the following condition . It may be a simplest solution for you but i will appreciate if you help me in this regard.


char *p="hello";
*(p+1) = ''A'';




该程序在第二行给出访问冲突错误.

即使我使用
,它也会给出相同的错误




This program gives Access violation error for second line.

It gives the same error even if i use

p[1]=''A'';

推荐答案

char *p = "hello";
char pArr[] = "Hello";



以上两个是不一样的.当您将其声明为指针并使用值对其进行初始化时,编译器会将其放入数据段 [ ^ ],然后在已初始化且只读"区域中.当您尝试更改此部分中存储的内容时,它应该会爆炸(这就是您所遇到的).

但是,后一个只是一个数组(内容存储在代码执行线程的堆栈中),因此可以根据需要更改内容.



The above two are not the same. When you declare it as a pointer and initialize it with a value, the compiler puts it in the Data Segment[^], AND in the "Initialised and read only" area. When you try to change contents stored in this section, it should blow up (that''s what you''re experiencing).

However, the latter one is just an array (the contents are stored in the code executing thread''s stack) and therefore the contents can be changed as you wish.


将字符串声明更改为char p[]="hello";.这应该允许您按索引访问p个元素;并且您始终可以通过输入第一个字符地址将其转换为char*
Change string declaration to char p[]="hello";. This should allow you to access p elements by index; and you can always turn it into char* by taking first character address


为什么要这样做?对我来说,这似乎是一个马戏团的把戏,而不是编程问题.您应该按索引访问p内的变量,而不是这样.
Why would you do this ? It looks like a circus trick to me, not a programming problem. You should access the variables inside p by index, not like this.


这篇关于简单代码的访问冲突错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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