gpt4 book ai didi

c - 关于修改 char * 元素的 SIGSEGV

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:07 26 4
gpt4 key购买 nike

<分区>

在下面的程序中,

#include<stdio.h>
#include<stdlib.h>
int main(){
const char *str1 = "abc";
char *str2 = (char *)malloc(sizeof(char)*4);
str2= "def";
str2[1]='s';
printf("str2 is %s", str2);

}

调试器:

(gdb) ptype str1                                                                                                                         
type = const char *
(gdb) ptype str2
type = char *
(gdb) n
7 str2[1]='s';
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x00000000004005ab in main () at main.c:7
7 str2[1]='s';
(gdb)

str2[1] = 's'; 上的 SIGSEGV

根据我的理解,由于声明 const char *st1 = "abc",不能修改 st1 指向的 abc,其中字符串文字是常量。

为什么 char * 类型 str2 不允许修改元素? stringliteral def 也是常量字符串文字吗。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com