简体   繁体   English

更改指针指向的字符的值

[英]Change value of character pointed by a pointer

I would like to know why my code giving me error when run. 我想知道为什么我的代码在运行时给我错误。

I am trying to change the character value pointed by a pointer variable. 我正在尝试更改指针变量指向的字符值。

#include <stdio.h>

int main() {
  char amessage[] = "foo";
  char *pmessage = "foo";

  // try 1
  amessage[0] = 'o'; // change the first character to '0'
  printf("%s\n", amessage);

  // try 2
  *pmessage = 'o'; // This one does not work
  printf("%s\n", pmessage);
}

The first attempt works, and prints ooo . 第一次尝试有效,并显示ooo But the second one gives me: 但是第二个给我:

[1]    9677 bus error  ./a.out

Any ideas? 有任何想法吗?

In this statement 在此声明中

*pmessage = 'o';

you are trying to change the string literal "foo" because the pointer is defined like 您正在尝试更改字符串文字"foo"因为指针的定义类似于

char *pmessage = "foo";

String literals are immutable in C and C++. 字符串文字在C和C ++中是不可变的。 Any attempt to change a string literal results in undefined behavior. 任何更改字符串文字的尝试都会导致未定义的行为。

From the C Standard (6.4.5 String literals) 根据C标准(6.4.5字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. 7不确定这些数组是否是唯一的,只要它们的元素具有适当的值即可。 If the program attempts to modify such an array, the behavior is undefined. 如果程序尝试修改这样的数组,则行为是不确定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM