数组和指针的区别,以字符串 [英] Difference between array and pointer to string literal

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

问题描述

我是新来的 C 的,所以它可能是一个愚蠢的问题。我写了一块code像波纹管:

I am new to C, so it may be a dumb question. I was writing a piece of code like bellow:

char ar[]="test";

*(ar+1)='r';

这是工作的罚款。但每当我这样做:

this is working fine. But whenever I am doing it:

char *p="test";

*(p+1)="r";

这是给人的分段故障的。任何人都可以请为什么第二种情况是给段错误描述?但从记忆点的解释将是AP preciated。

this is giving segmentation fault. Can anyone please describe why second case is giving segmentation fault? explanation from memory point of view will be appreciated.

推荐答案

在第二种情况下 P 指向一个的字符串的你不允许修改的字符串的,它是未定义行为。从 C99标准草案部分 6.4.5 字符串字面的段落的 6 的(重点煤矿的):

In the second case p is pointing to a string literal and you are not allowed to modify a string literal, it is undefined behavior. From the C99 draft standard section 6.4.5 String literals paragraph 6 (emphasis mine):

这是不确定的,这些阵列是否提供了不同的元素都在
  适当的值。 如果该程序试图修改这样的阵列,该行为是
  未定义

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

在第一种情况下 AR 是一个自动变量,你可以修改它,因为它没有的常量的资格。的内容的字符串的初始化期间被复制或 AR

In the first case ar is an automatic variable and you are allowed to modify it since it not const qualified. The contents of the string literal are being copied during initialization or ar.

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

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