指針間接賦值,指針賦值
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*間接賦值成立的三個條件:
條件一://定義一個實參 //定義一個形參
條件二://建立關聯:把實參取地址傳給形參
條件三://形參間接去修改實參的值
*/
/*
用n級指針形參,去間接的修改n-1級指針(實參)的值。
*/
/*間接賦值的場景
//1 2 3 這3個條件 寫在有一個函數
//12 寫在一塊 3 單獨寫在另外一個函數裡面 =====>函數調用
//1 23寫在一塊
void main()
{
char from[128];
char to[128] = {0};
char *p1 = from;
char *p2 = to;
strcpy(from, "1122233133332fafdsafas");
while (*p1 != '\0')
{
*p2 = *p1;
p2 ++;
p1++;
}
printf("to:%s \n", to);
}
*/
int getMem3(char **myp1, int *mylen1, char **myp2, int *mylen2)
{
int ret = 0;
char *tmp1, *tmp2;
tmp1 = (char*)malloc(100);
strcpy(tmp1, "1234456789");
*mylen1 = strlen(tmp1); //1級指針
*myp1 = tmp1; //2級指針的間接賦值
tmp2 = (char*)malloc(200);
strcpy(tmp2, "abcdefghigklmn");
*mylen2 = strlen(tmp2);//1級指針
*myp2 = tmp2;//2級指針的間接賦值
return ret;
}
int main()
{
char *p1 = NULL;
char *p2 = NULL;
int len1 = 0;
int len2 = 0;
int ret = getMem3(&p1,&len1,&p2,&len2);
if (ret !=0){
printf("func getMem3 %d",ret);
return ret;
}
printf("p1:%s\n", p1);
printf("p2:%s\n", p2);
if (p1 != NULL)
{
free(p1);
p1 = NULL;
}
if (p2 != NULL)
{
free(p2);
p2 = NULL;
}
system("pause");
return 0;
}