在C字符串文字forbiddens [英] forbiddens in string literals in C

查看:129
本文介绍了在C字符串文字forbiddens的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在K&放大器; R书第104页,我碰到这个声明是:


 字符amessage [] =现在是时候了; //数组
字符* pmessage =现在是时候了; //指针


  
  

在阵列中各个字符可能会改变,但 amessage
  将始终指的是相同的存储。在 pmessage 指针可能
  随后被修改为指向其他,但结果是
  不确定的,如果你尝试修改字符串的内容...


那么,这会是他们在这两种情况下意味着错误?

对于数组,

  amessage [] =分配给另一个地址; //错误?

有关指针,

  pmessage [0] ='N'; //错误?

我只是想知道当一个人违背这些规则。

感谢。


解决方案

  / * OK,修改由数组初始化
 *字符串文字的元素* /
amessage [0] ='N';/ *也不行,修改字符串。
 *字符串文字是不可修改的* /
pmessage [0] ='N';

请注意,在C你不能指定数组,所以如果你想复制一个阵列中使用的memcpy 功能或使用的strcpy 的功能来复制一个字符串。

In the K&R book page 104, I came across this statement:

char amessage[] = "now is the time"; //an array
char *pmessage = "now is the time";  //a pointer

Individual characters within the array may be changed but amessage will always refer to the same storage. The pmessage pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents...

So, would this be the error they meant in both cases?

For the array,

amessage[] = "allocate to another address"; //wrong?

For the pointer,

pmessage[0] = 'n'; //wrong?

I just want to know when one is going against these rules.

Thanks.

解决方案

/* OK, modifying an array initialized by the 
 * elements of a string literal */
amessage[0] = 'n';

/* not OK, modifying a string literal.
 * String literals are non-modifiable */
pmessage[0] = 'n';

Note that in C you cannot assign arrays, so if you want to copy an array use memcpy function or use strcpy function to copy a string.

这篇关于在C字符串文字forbiddens的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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