字符指针的运用
#include<stdio.h>
Int main()
{
Char b[]=”hello”;
Char *a=”hello”;
Char *c=b;
//a=’w’;错误
//*a=”wello”;错误
//a[0]=’w’;错误
b[0]=’w’;//和c[0]=’w’;的作用是一样的,都是改变了b[0];
c[0]=’w’;
Printf(“the address of a is %p\n”,a);
Printf(“the address of b is %p\n”,b);
Printf(“the address of c is %p\n”,c);
Printf(“the address of “hello” is %p\n”,”hello”);
Printf(“a is %s\n”,a);
Printf(“b is %s\n”,b);
Printf(“c is %s\n”,c);
Return 0;
}
运行结果:
the address of a is 0x80485e0
the address of b is 0xbfc30ad6
the address of c is 0xbfc30ad6
the address of hello is 0x80485e0
a is hello
b is wello
c is wello
看下面的内容首先要知道程序中的*a和*c是不同的而两个值,指针变量a指向的是常量“hello“的首地址,而c放的是字符数组b[]的首地址即:c=&b[0]。
1. 结果显示的是a的地址和“hello”的地址相同的,他们是同一个地址空间,但是他们和b之间的地址确实不相同的,而且你运行多次你会发现a和“hello”的地址是不发生变化的,因为“hello”是字符常量,是不可以改变的,b数组的地址是在每次运行时系统会自动的分配一个数组空间用来存放数组b,所以每都是不同的。但b和c的地址是相同的。
2. 当我们要对数组b的值进行改变是可以用 b[i]=’w’;此时b[0]=’w’;是正确的。而要改变a指针指向的”hello”的值,因为此时的”hello ”是一字符串常量,是不可以改变的。所以a=’w’; *a=”hello”; a[0]=”w”;这些都是错误的。
3. 把上面的指针初始化为Char *c=b;这样c[i]和b[i]的用法就是一样的了c[0]的值也就是b[0]的值,这样就可以用c[0]=’w’;来改变数组b[0]的值,输出的是whell,这样就改变了数组b的第一个是b[0];这样我们就可以用指针来改变字符串数组中的任何一个字符了。