无法更改字符串文字Via指针中的字符

时间:2014-09-02 14:26:30

标签: c pointers

我正在尝试使用指针分配一个字符,但它没有。

有人请解释为什么以下程序停止工作?

#include <string.h>

int main(void) {
  char *s = "modifying...";
  // char s2[] = {'m','o','d','i','f','y','i','n','g','.','.','.',NULL};
  // s = s2;
  puts(s);
  *s = 'M'; // Here the program stops working
  puts(s);
  return 0;
}

3 个答案:

答案 0 :(得分:1)

您不能以这种方式更改字符串文字。

https://stackoverflow.com/a/17507772/234307

&#34; C字符串文字创建一个匿名的char数组。任何修改该数组的尝试都有未定义的行为。&#34; - 基思汤普森

答案 1 :(得分:0)

尽管C中的字符串文字具有非常量字符数组的类型,但它们是不可变的。您可能无法更改字符串文字。 改为使用

char s[] = "modifying...";

答案 2 :(得分:0)

字符串文字本身位于函数外部的内存中。你想要做的是为可修改的字符串分配一个缓冲区...

char *pszLiteral = "literal";
char *pszBuffer = (char *)malloc(strlen(pszLiteral) + 1);
strcpy(pszBuffer, pszLiteral); // copy the literal value located at pszLiteral to the buffer pszBuffer, which is modifiable (located on heap)
*pszBuffer = 'L'; // or pszBuffer[0] = 'L';
puts(pszBuffer);
free(pszBuffer);

或者您可以使用位于堆栈上的静态缓冲区而不是堆

char *pszLiteral = "literal";
char pszLocal[20];
strcpy(pszLocal, pszLiteral);
*pszLocal = 'L'; // or pszLocal[0] = 'L';
puts(pszLocal);
相关问题