C语言高级编程:字符串赋值的几种方式

C语言高级编程:字符串赋值的几种方式

1. 总结

1)下面两种方式的字符串赋值均正确

char str1[] = "hello str1";

char *str2 = "hello str2";

char *str3; str3 = "hello str3";

2)char str1[] = "hello str1"; 是将字符串赋值给数组,字符串存在数组里(这里是栈),可以修改字符串内容,可读可写。

3) char *str2 = "hello str2"; 是将字符串地址赋值给指针变量,字符串本身存在只读内存区,不可通过指针对其进行修改,只读不可写。

4)str3 = "hello str3"; 同3)

2. 代码:

#include

#include

void main(void)

{

char str1[] = "hello str1";

char *str2 = "hello str2";

//str1[0] = 'a';

//str2[0] = 'a';

printf("str1: %s\n", str1);

printf("str2: %s\n", str2);

}

3. 结果:

baoli@ubuntu:~/c$ ./a.out

str1: hello str1

str2: hello str2

将上述代码两行注释去掉,编译,运行:

baoli@ubuntu:~/c$ ./a.out

Segmentation fault (core dumped)

4. gdb调试:gdb ./a.out

(gdb) run

Starting program: /home/baoli/c/a.out

warning: the debug information found in "/lib64/ld-2.19.so" does not match "/lib64/ld-linux-x86-64.so.2" (CRC mismatch).

Program received signal SIGSEGV, Segmentation fault.

0x00000000004005dc in main () at test.c:11

11 str2[0] = 'a';

(gdb)

(gdb) print str2

$1 = 0x4006b4 "hello str2"

(gdb) print str1

$2 = "aello str1"

相关推荐

WLK怀旧服采矿速冲450攻略 以熔炼为主升级方案
www365bet娱乐场

WLK怀旧服采矿速冲450攻略 以熔炼为主升级方案

📅 07-12 👀 128
另字笔画写法
www365bet娱乐场

另字笔画写法

📅 07-19 👀 9892
相框软件哪个好?美化照片软件哪个好
www365bet娱乐场

相框软件哪个好?美化照片软件哪个好

📅 07-06 👀 4448
iPad(第 10 代)
www365bet娱乐场

iPad(第 10 代)

📅 07-04 👀 5135