指针进阶-字符指针、指针数组
字符指针
字符指针char* 是指针的一种类型。
存储一个字符:
int main()
{
char ch='w';
char* pc=&ch;
*pc='w';
return 0;
}
存储字符串:本质上是把字符串的首字符的地址存储在指针中。它与数组不一样,数组是将字符串全部存在数组内。
int main()
{
char* ps = "hello world";
printf("%c\n", *ps);//结果是h
printf("%s\n", ps);//结果是hello world
return 0;
}
思考:下面代码的运行结果。
int main()
{
char str1[] = "hello world!";
char str2[] = "hello world!";
const char *str3 = "hello world!";
const char *str4 = "hello world!";
if(str1 == str2)
printf("sre1 and str2 are same\n");
else
printf("sre1 and str2 are not same\n");
if(str3 == str4)
printf("sre3 and str4 are same\n");
else
printf("sre3 and str4 are not same\n");
return 0;
}
结果:
sre1 and str2 are not same
sre3 and str4 are same
为什么呢?
对于str1[]和str2[],它们是两个数组,分别在内存中开辟了两块空间存储"hello world!"。而str1和sre2是数组名,代表数组首元素的地址,所以str1和str2不是'h',而是'h'的地址。str1[]和str2[]是两个不同的空间,首元素的地址自然不同。
"hello world!"是一个常量字符,存储在字符指针里就不能在更改了,对于这种不能更改的常量字符。内存中只会存储一次,也就是说 * str3和 * str4两个字符指针共用一个数据。而字符指针本质上是把字符串的首字符的地址存储在指针中,所以 * str3和 * str4是相等的。
指针数组
指针数组本质上是数组,里面存放的是指针(地址)。
指针数组的使用方法:
int main()
{
int a=10;
int b=5;
int c=3;
int *arr[3]={&a, &b, &c};
for(int i=0; i<3; i++)
{
printf("%d ", *(arr[i]));
}
return 0;
}
上面的代码是一种使用的方法,但是并没有什么使用,而且代码也显得很low。
int main()
{
int a[5]={1,2,3,4,5};
int b[]={2,3,4,5,6};
int c[]={3,4,5,6,7};
//存储
int *arr[3]={a,b,c};
//打印
for(int i=0; i<3; i++)
{
for(int j=0; j<5; j++)
{
print("%d ", *(arr[i]+j));//i行下表为j的地址
//print("%d ", *(arr[i][j]));与上一句等价
}
}
return 0;
}
上面是第二种使用,数组名是首元素的地址,通过数组名把三个数组存放在指针数组中。同样可以打印出a,b,c三个数组。但是这种方法并不是二维数组,它和二维数组有不同之处,二维数组中的每一行是连续的,而这里的每一行是独立的。