C语言-指向指针的指针

  • 2020-10-04
  • 0
  • 0

一、指向指针的指针

#include <stdio.h>
int main()
{
	int num = 520;
	int *p = #
	int **pp = &p;

	printf("num %d\n", num);
	printf("*p %d \n", *p);
	printf("**pp %d \n", **pp);
	printf("&p %p, pp %p\n", &p, pp );
	printf("&num %p, p %p, *pp %p\n", &num, p, *pp);
	return 0;

}

二、指针数组和指向指针的指针

1.指向指针的指针的作用:

用指向指针的指针来指向数组指针

#include <stdio.h>
int main()
{
	char *cBooks[] = {
		"《C语言程序设计》",
		"《C专家编程》",
		"《C和指针》",
		"《C陷阱与缺陷》",
		"《C Primer Plus》",
		"《带你学C带你飞》"};
	char **byFishC;
	char **Loves[4];
	int i;

	byFishC = &cBooks[5];
	Loves[0] = &cBooks[0];
	Loves[1] = &cBooks[1];
	Loves[2] = &cBooks[2];
	Loves[3] = &cBooks[3];
	printf("FishC出版的图书有: %s\n", *byFishC);
	printf("喜欢的图书有:\n");

	for (i = 0; i < 4; i++)
		printf("%s\n",*Loves[i]);
	
	return 0;
}

2.两个好处:

——避免重复分配内存

——只需要进行一处修改

提高了代码的灵活性和可靠性

三、数组指针和二维数组

1.通过指针对一维数组进行索引没有问题

#include <stdio.h>
int main()
{
	int array[10] = {0,1,2,3,4,5,6,7,8,9};
	int *p = array;
	int i;

	for (i = 0; i < 10; i++)
	{
		printf("%d\n",*(p+i));
	}


	return 0;


}

2.通过指针对维二维数组进行索引有问题

#include <stdio.h>
int main()
{
	int array[3][4] = {
		{0,1,2,3},
		{4,5,6,7},
		{8,9,10,11}};
	int **p = array;
	int i,j;

	for (i = 0; i < 3; i++)
	{
		for(j = 0; j < 4; j++)
		{	
			printf("%2d",*(*(p+i)+j));
		}
		printf("\n");
	}


	return 0;


}

这样又是正常的

#include <stdio.h>
int main()
{
	int array[3][4] = {
		{0,1,2,3},
		{4,5,6,7},
		{8,9,10,11}};
	//int **p = array;
	int i,j;

	for (i = 0; i < 3; i++)
	{
		for(j = 0; j < 4; j++)
		{	
			printf("%2d",*(*(array+i)+j));
		}
		printf("\n");
	}


	return 0;


}

为什么呢?

#include <stdio.h>
int main()
{
	int array[3][4] = {
		{0,1,2,3},
		{4,5,6,7},
		{8,9,10,11}};
	int **p = array;
/*	int i,j;

	for (i = 0; i < 3; i++)
	{
		for(j = 0; j < 4; j++)
		{	
			printf("%2d",*(*(array+i)+j));
		}
		printf("\n");
	}
*/
	printf("p: %p, array: %p\n", p, array);
	printf("p+1: %p, array+1: %p\n", p+1, array+1);

	return 0;


}

错误原因:因为c语言的p+1只加了4个字节并不和array+1相同

3.如何通过用指针索引二维数组?

数组指针

#include <stdio.h>
int main()
{
	int array[3][4] = {
		{0,1,2,3},
		{4,5,6,7},
		{8,9,10,11}};
	int (*p)[4] = array;
	int i,j;

	for (i = 0; i < 3; i++)
	{
		for(j = 0; j < 4; j++)
		{	
			printf("%2d",*(*(p+i)+j));
		}
		printf("\n");
	}


	return 0;


}

因为跨度相同所以可以用数组指针索引二维数组

评论

还没有任何评论,你来说两句吧