我如何修改char *的值? [重复]

时间:2021-05-20 17:04:06

This question already has an answer here:

这个问题在这里已有答案:

Hi i have below program.

嗨,我有以下程序。

char *x="abc";
*x=48;
printf("%c",*x);

This gives me output a, but I expected output as 0.

这给了我输出a,但我预计输出为0。

EDIT Can you suggest what I can do in order to store data during runtime in

编辑你可以建议我在运行时在存储数据时可以做些什么

char *x;

2 个解决方案

#1


4  

You can't: the behaviour on attempting to is undefined. The string "abc" is a read-only literal (formally its type is const char[4]).

你不能:尝试的行为是未定义的。字符串“abc”是只读文字(形式上它的类型是const char [4])。

If you write

如果你写

char x[] = "abc";

Then you are allowed to modify the string.

然后你可以修改字符串。

#2


1  

You cannot (even try to) to modify a string literal. It causes undefined behavior.

你不能(甚至尝试)修改字符串文字。它会导致未定义的行为。

You need to make use of a write-allowed memory. There are two ways.

您需要使用允许写入的内存。有两种方法。

  • Allocate memory to pointer x (i.e, store the returned pointer via memory allocator methods to x), then this will be writable, and copy the string literal using strcpy().

    将内存分配给指针x(即,通过内存分配器方法将返回的指针存储到x),然后这将是可写的,并使用strcpy()复制字符串文字。

      char * x = NULL;
      if (x = malloc(DEF_SIZ)) {strcpy(x, "abc");}
    
    • Or, not strictly standard conforming, but shorter, strdup().

      或者,不是严格的标准符合,而是更短,strdup()。

      char *x = strdup("abc");
      
  • use an array x and initialize it with the string literal.

    使用数组x并使用字符串文字初始化它。

    char x[] = "abc";
    

In all above cases, x (or rather, the memory location pointed by x) is modifiable.

在所有上述情况中,x(或更确切地说,x指向的存储器位置)是可修改的。

#1


4  

You can't: the behaviour on attempting to is undefined. The string "abc" is a read-only literal (formally its type is const char[4]).

你不能:尝试的行为是未定义的。字符串“abc”是只读文字(形式上它的类型是const char [4])。

If you write

如果你写

char x[] = "abc";

Then you are allowed to modify the string.

然后你可以修改字符串。

#2


1  

You cannot (even try to) to modify a string literal. It causes undefined behavior.

你不能(甚至尝试)修改字符串文字。它会导致未定义的行为。

You need to make use of a write-allowed memory. There are two ways.

您需要使用允许写入的内存。有两种方法。

  • Allocate memory to pointer x (i.e, store the returned pointer via memory allocator methods to x), then this will be writable, and copy the string literal using strcpy().

    将内存分配给指针x(即,通过内存分配器方法将返回的指针存储到x),然后这将是可写的,并使用strcpy()复制字符串文字。

      char * x = NULL;
      if (x = malloc(DEF_SIZ)) {strcpy(x, "abc");}
    
    • Or, not strictly standard conforming, but shorter, strdup().

      或者,不是严格的标准符合,而是更短,strdup()。

      char *x = strdup("abc");
      
  • use an array x and initialize it with the string literal.

    使用数组x并使用字符串文字初始化它。

    char x[] = "abc";
    

In all above cases, x (or rather, the memory location pointed by x) is modifiable.

在所有上述情况中,x(或更确切地说,x指向的存储器位置)是可修改的。