这两天在学习扫地僧的课程(二级指针三种内存模型)时,最后的作业是把“第一种内存模型和第二种内存模型的内容复制到第三种内存模型中,并进行排序”。老师预定义了前两种内存模型的内容,和对应的函数实现接口,如下:
char *p1[] = { "aaaaa", "cccccc", "bbbbb" };
char buf2[10][30] = { "111111", "3333333", "2222222" };
函数接口:
int sort(char ** myp1/*in*/, int num1/*in*/, char(*myp2)[30]/*in*/, int num2/*in*/, char ***myp3/*out*/, int *pNum3/*out*/);
既然老师希望在sort()函数解决问题,我的思路是:
先获得传入的两个字符串数组中,最长的字符串长度;
取两个输入的字符串数组的成员数量之和,并且获得最长的那个字符串的长度之后,根据这两个参数再堆上申请空间;
分别复制两个字符串数组到新的堆空间上;
针对堆空间的字符串数组进行排序,最后输出排好序的字符串。
释放申请的堆空间。
思路还比较清晰,然后就自己实现代码了。首先我自己定义的函数接口为:
// 获取最长的字符串长度
int getRowLen(char **myp1/*in*/, int num1/*int*/, int *pLen)
// 申请堆空间
int getArray3(char ***p, int RowNum, int RowLen)
// 复制字符串数组
int copyArray(char **myp1/*in*/, int num1/*in*/, char **myp3/*in*/, int *pMyp3Row/*in, out*/)
// 释放堆空间
int getArray3_Free(char ***p3, int p3num)
// 最后是题目给定的函数接口,主要功能在该函数中实现
int sort(char ** myp1/*in*/, int num1/*in*/, char(*myp2)[30]/*in*/, int num2/*in*/, char ***myp3/*out*/, int *pNum3/*out*/)
测试案例如下:
int main()
{
int nRet = 0;
char *p1[] = { "aaaaa", "cccccc", "bbbbb" };
char buf2[10][30] = { "111111", "3333333", "2222222" };
char **p3 = NULL;
int len1, len2, len3, i = 0;
len1 = sizeof(p1) / sizeof(*p1);
len2 = 3;
nRet = sort(p1, len1, buf2, len2, &p3, &len3);
if (nRet != 0) {
printf("func sort() err: %d \n", nRet);
return nRet;
}
printf("after sorting...\n");
for (; i < len3; i++) {
printf("%s \n", p3[i]);
}
getArray3_Free(&p3, len3);
system("pause");
}
在编译的时候就遇到了困惑,编译器报错:
Error C2664 'int copyArray(char **,int,char **,int )': cannot convert argument 1 from 'char ()[30]' to 'char **'
我在追溯问题的时候一直以为是指针传输的问题,但是想不到更具体的可疑点。最后在做实验的时候发现,有两个函数接口有同样的问题,getRowLen() 和 copyArray()都是把试图原数组的地址传进来,可是,每次传入的数组是buf2[10]
[30]的时候就会报错,原因在于:
设计的函数参数列表中没有指定确定的维度信息,在传输buf2[10][30]的时候,因为sort()指定了维度信息char(myp2)[30],所以编译器知道myp2的第二维是30个char类型的长度,至于myp2中有多少个字符串,在传入myp2的时候编译器必然是已经计算