C语言中char *p与char p[]的区别

最近写程序遇到一个比较离奇 的程序
简单如下:
 char *p="abc";
 *(p+1)='B';
 puts(p);
居然不对,没有正确的运行结果,后来在网络上查到了,原来是C语言中内存单元分区问题。
/*下面内容来自网络*/
  一个由C/C++编译的程序占用的内存分为以下几个部分  
  1、栈区(stack)—   由编译器自动分配释放   ,存放函数的参数值,局部变量的值等。其  
  操作方式类似于数据结构中的栈。  
  2、堆区(heap)   —   一般由程序员分配释放,   若程序员不释放,程序结束时可能由OS回收   。注意它与数据结构中的堆是两回事,分配方式倒是类似于链表。  
  3、全局区(静态区)(static)—,全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域,未初始化的全局变量和未初始化的静态变量在相邻的另一块区域。程序结束后由系统释放。  
  4、文字常量区   — 常量字符串就是放在这里的。程序结束后由系统释放 。 
  5、程序代码区—存放函数体的二进制代码。
=========================
另:
相关解释:
C99标准   第130页  
   
  32   EXAMPLE   8   The   declaration  
  char   s[]   =   "abc",   t[3]   =   "abc";  
   
  defines   "plain"   char   array   objects   s   and   t   whose   elements   are   initialized   with   character   string    
  literals.  
   
  This   declaration   is   identical   to  
  char   s[]   =   {   'a',   'b',   'c',   '\0'   },  
  t[]   =   {   'a',   'b',   'c'   };  
  The   contents   of   the   arrays   are   modifiable.    
   
  On   the   other   hand,   the   declaration  
  char   *p   =   "abc";  
  defines   p   with   type   "pointer   to   char"   and   initializes   it   to   point   to   an   object   with   type
   
  "array   of   char"   with   length   4   whose   elements   are   initialized   with   a   character   string   literal.    
  If   an   attempt   is   made   to   use   p   to   modify   the   contents   of   the   array,   the   behavior   is   undefined.  
所以在char*   p   =   "abc";   中
  C语言标准并没有规定是否可以通过p修改"abc",  
  如果用p修改"abc",那么行为是未定义的  
  在某些编译器下会正确  
  在某些编译器下会错误
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章