指针理解

#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<string.h>
#include<stdio.h>

void func1(char** p2) //p2来接收p1的地址
{ 
	*p2 = 400;        //修改p2指向地址存放的数据(修改p1)
}
void func2(char* p2) //p2(一级指针)来接p1(一级指针)
{
	p2 = 500;        //修改p2的值,不会影响p1 要修改p1的数据必须通过二级指针
}
void main()
{

	char *p1 = NULL;   //p1是一级指针,是变量  4B
	char **p2 = NULL;  //p2是二级指针,是变量  4B
	
	p1 = 100;  //p1存放100
	p2 = 200;  //p2存放200
	p2 = &p1;  //p2存放p1的地址

	printf("p1:%d
",p1);  //100
	
	*p2 = 300;             //修改p2指向地址存放的数据(修改p1)
	printf("p1:%d
", p1); //200

	func1(&p1);            //p1的地址
	printf("p1:%d
", p1); //400

	func2(p1);             //p1
	printf("p1:%d
", p1); //400

	system("pause");
	return ;
}

 

 2.

int getNum(char **myp1, int *len1 , char  **myp2 , int *len2)
{
	int ret = 0;
	char *p1 = NULL;
	char *p2 = NULL;
	p1 = (char*)malloc(100); //p1开辟内存空间,100字节
	p2 = (char*)malloc(100); //p2开辟内存空间,100字节
	strcpy(p1,"aaaaaaaa"); //向p1指向的内存空间拷贝数据
	strcpy(p2, "abfasfsafas"); 
	*len1 = strlen(p1); //求长度
	*len2 = strlen(p2); 
	*myp1 = p1;   //修改实参的数据(间接赋值)
	*myp2 = p2;  
	return ret;
}
void main()
{
	char *p1 = NULL;
	char *p2 = NULL;
	int len1 = 0;
	int len2 = 0;
	int ret=getNum(&p1,&len1,&p2,&len2);
	if (ret != 0)
	{
		printf("getNum() err");
		return 0;		
	}
	printf("p1:%s
",p1); //p1为字符串的开始地址 *p1为一个字节,只能用%c输出
	printf("size:%d
", len1);
	printf("p2:%s
",p2);  //p2为字符串的开始地址
	printf("size:%d
", len2);
	if (p1 != NULL)
	{
		free(p1);
		p1 = NULL;
	}
	if (p2 != NULL)
	{
		free(p2);
		p2 = NULL;
	}
	system("pause");
	return 0;
}

3.二级指针做函数输入

#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
//输入数组元素 void printMyArray(char **myArray, int num) //二级指针做输入 接收 指针数组 { int i; for (i = 0; i < num; i++) { //printf("%s",myArray[i]); // myArray[i]代表指针元素 和 *(myArray+i)相同 printf("%s ", *(myArray+i)); // } return; } //排序 void mySort(char** myArray, int num) //二级指针做输入 { char * tmp = NULL; //tmp指针做中间变量 int i, j = 0; for (i = 0; i < num; i++) //选择排序 { for (j = i; j < num; j++) { if (strcmp(myArray[i], myArray[j]) > 0) { tmp = myArray[i]; myArray[i] = myArray[j]; myArray[j] = tmp; } } } return; } void main() { int num; char* myArray[] = {"aaaaaaaaaaaa","cccccc","bbbbbb","ccccccc","ddddddd"}; //定义一个指针数组,存放指针变量 //printf("%d ",sizeof(myArray)); //myArray为数组大小 指针4B*5=20 //printf("%d ", sizeof(myArray[0])); //myArray[0]为第一个指针变量的大小4B num = sizeof(myArray) / sizeof(myArray[0]); //求出指针数组有多少个元素 printf("排序之前 "); printMyArray(myArray,num); mySort(myArray,num); printf("排序之后 ");
     printMyArray(myArray, num);
     char **p;
	p = (char**)malloc(sizeof(char*)*num); //开辟(char*大小)*num的内存空间,p指向开头
	if (p == NULL)
	{
		return NULL;
	}
	for (int i = 0; i < num; i++)
	{
		p[i] = (char*)malloc(sizeof(char) * 100); 开辟char大小*100字节的内存空间,p[i]分别指向各自的首地址
		sprintf(p[i], "the %d string", num - i);
	}
     printf("排序之前
");
	printMyArray(myArray,num);
	mySort(myArray,num);
	printf("排序之后
");
}

 

二级指针内存模型

 

 

原文地址:https://www.cnblogs.com/sclu/p/11271070.html