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 <stdio.h>
#include <stdlib.h>
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"
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论