黑马程序员技术交流社区
标题:
针对字符和字符串是否可以修改. 详解,附代码
[打印本页]
作者:
叶子哥
时间:
2016-4-24 08:42
标题:
针对字符和字符串是否可以修改. 详解,附代码
// 1.对字符变量可以直接重新赋值进行修改.
char ch1 = 'b';
printf("ch1的地址是: %p\n",&ch1);
ch1 = 'T';
printf("ch1 = %c\n",ch1);
printf("ch1的地址是: %p\n",&ch1);
// 2.ch2[4] = {'a','b','c','d'};对这样赋值的字符数组可以直接重新赋值进行修改
char ch2[4] = {'a','b','c','d'};
printf("ch2[1] address:%p\n",&ch2[1]);
printf("ch2[2] address:%p\n",&ch2[2]);
ch2[1] = 'g',ch2[2] = 'h';
for (int i=0; i<4; i++) {
printf("%c\t",ch2[i]);
}
printf("\n");
printf("ch2[1] address:%p\n",&ch2[1]);
printf("ch2[2] address:%p\n",&ch2[2]);
// 3.ch3[4] = "abcd";对这样赋值的字符数组可以直接重新赋值进行修改
char ch3[4] = "abcd";
printf("ch3[1] address:%p\n",&ch3[1]);
printf("ch3[2] address:%p\n",&ch3[2]);
ch3[1] = 'g',ch3[2] = 'h';
for (int i=0; i<4; i++) {
printf("%c\t",ch3[i]);
}
printf("\n");
printf("ch3[1] address:%p\n",&ch3[1]);
printf("ch3[2] address:%p\n",&ch3[2]);
// 4.*ch4 = "abcd";对这样赋值的字符指针不可以重新赋值进行修改,运行时会报错.此时"abcd"存储在数据区中,为字符串常量,不可对其修改.
char *ch4 = "abcd";
printf("ch4[1] address:%p\n",&ch4[1]);
printf("ch4[2] address:%p\n",&ch4[2]);
ch4[1] = 'g',ch4[2] = 'h';
for (int i=0; i<4; i++) {
printf("%c\t",ch4[i]);
}
printf("\n");
printf("ch4[1] address:%p\n",&ch4[1]);
printf("ch4[2] address:%p\n",&ch4[2]);
// 5.char *ch5 = &chr;对单个字符指针,可以对其进行修改.此时ch5指针指向的是栈区的一块内存
char chr = 'b';
char *ch5 = &chr;
printf("ch5 :%c\n",*ch5);
printf("ch5 address:%p\n",ch5);
*ch5 = 'h';
printf("ch5 new:%c\n",*ch5);
printf("ch5 new address:%p\n",ch5);
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2