二级指针做输入
#include<stdio.h> #include<string.h> #include<stdlib.h> int getMem(char **myp1,int *mylen1,char **myp2,int *mylen2) { char *tmp1 = NULL; char *tmp2 = NULL; tmp1 = (char *)malloc(100); if(tmp1 == NULL) { return -1; } strcpy(tmp1,"abcdefg"); *mylen1 = strlen(tmp1); *myp1 = tmp1; tmp2 = (char *)malloc(100); if(tmp2 == NULL) { return -1; } strcpy(tmp2,"abcdefg"); *mylen2 = strlen(tmp2); *myp2 = tmp2; return 0; } int getMem_free(char **myp1) { char *tmp = NULL; if(myp1 == NULL) { return; } tmp = *myp1; free(tmp); *myp1 = NULL; return 0; } int main() { char *p1 = NULL; int len1 = 0; char *p2 = NULL; int len2 = 0; int iRet = 0; iRet = getMem(&p1,&len1,&p2,&len2); printf("p1 : %s \n",p1); printf("p2 : %s \n",p2); getMem_free(&p1); getMem_free(&p2); return 0; }
二级指针做输入,利用指针改变指针指向内容
#include<stdio.h> #include<stdlib.h> #include<string.h> void printMyarray(char **myArray,int num) { int i; for(i = 0; i < num; i++) { //printf("%s \n",myArray[i]); printf("%s \n",*(myArray+i)); } } void sortMyarray(char **myArray,int num) { int i = 0, j = 0; char *tmp = NULL; 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; } } } } int main() { int i = 0, j = 0; int num = 0; char *myArray[] = {"aaaaa","bbbbb","ccccl","1111111"}; num = sizeof(myArray)/sizeof(myArray[0]); printMyarray(myArray,num); sortMyarray(myArray,num); printf("after sort\n"); printMyarray(myArray,num); return 0; }
如果将main函数中的字符串数组声明修改为
char myArray[10][30] = {"aaaaa","bbbbb","ccccl","1111111"};
此时,在传入打印和排序的函数中仍然使用char ** myArray 来声明形参的话,会出现报错,原因是指针的步长不一样,而且指针指向的内存空间数据类型也不一样。
原文地址:https://www.cnblogs.com/wanghao-boke/p/11625365.html
时间: 2024-10-10 08:46:59