0
char * str = "Hello";

*(str+1) = '3';

cout<<str;

我试图做的是把第二个字符变成'3',把它变成H3llo

为什么它不起作用?

4

6 回答 6

3

这是未定义的行为。你不能改变文字。

要有一个指向文字的指针,它应该是:

  const char* str = "Hello";
//^^^^^

然后,为了能够更改字符串,这应该是,例如

char str[] = "Hello";

另一种选择是动态分配内存(使用mallocand free

于 2012-08-13T07:18:25.117 回答
2

字符串文字被分配在只读内存中。所以基本上它们是类型(const char *)。它不能改变。另请参阅以获取更多信息。

于 2012-08-13T07:18:21.107 回答
1

因为 str 的类型是“const char *”,并且不允许覆盖它指向的对象。

于 2012-08-13T07:18:03.823 回答
0
#include <string.h>
char *str;
if((str = malloc(strlen("hello"))) != NULL)
  return (null);
str = strcpy(str, "hello");
printf("%s\n", str); // should print hello
str[2] = '3';
printf("%s\n", str) // should print he3lo

这里的事情是我在字符串中设置 char 之前分配内存。但是,如果您不擅长分配,您可以随时设置 char str[] = "hello";

于 2012-08-13T07:27:23.783 回答
0

内存str将在.rodata部分中分配。所以试图修改只读数据会产生问题。

以下问题给出了问题。

#include <stdio.h>

int main()
{
char * str = "Hello";

printf("\n%s \n", str);
*(str+1) = '3';
printf("\n%s \n", str);


return 0;
}

相应的拆卸

 .file   "dfd.c"
        .section        .rodata
.LC0:
        .string "Hello"
.LC1:
        .string "\n%s \n"
        .text
  .....
  .....

结果是

Hello 
Segmentation fault (core dumped)

我在 X86_64 上使用 gcc 版本 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)。

于 2012-08-13T09:24:07.713 回答
0

str 是指向字符串常量的指针,字符串的内存在只读部分中分配。如果您尝试修改字符串内容,则结果未定义。但是,与始终绑定到相同内存位置的数组名称相比,您可以修改指针以指向其他内容。

于 2012-08-14T03:51:04.067 回答