复制字符串而不是直接赋值指针
(LeetCode:2418.按身高排序)
1.why?
数据独立性:
复制字符串使返回结果与输入数据完全独立
修改返回数组中的字符串不会意外影响原始数据(可移植性)
原始数据被释放后,返回结果仍然有效内存安全:
- 避免悬垂指针问题(如果原始数组被释放)
- 符合"caller负责free"的接口约定(返回完全独立的内存块)
2.示例:
(1)直接复制指针:
/** * Note: The returned array must be malloced, assume caller calls free(). */#defineunlikely(x)__builtin_expect(!!(x),0)intcmp(constvoid*a,constvoid*b){int*rwna=(*(int**)a);int*rwnb=(*(int**)b);returnrwnb[0]-rwna[0];//降序排列}char**sortPeople(char**names,intnamesSize,int*heights,intheightsSize,int*returnSize){*returnSize=0;//分配空间来存储,第一个储存升高,第二个存储下标int**ret=(int**)malloc(sizeof(int*)*heightsSize);if(unlikely(!ret)){returnNULL;}for(inti=0;i<heightsSize;i++){ret[i]=(int*)malloc(sizeof(int)*2);if(unlikely(!ret[i])){for(intk=0;k<=(*returnSize);k++){free(ret[k]);}free(ret);returnNULL;}ret[i][0]=heights[i];ret[i][1]=i;(*returnSize)++;}//二维数组排序qsort(ret,heightsSize,sizeof(int*),cmp);char**ans=(char**)malloc(sizeof(char*)*heightsSize);if(unlikely(!ans)){returnNULL;}for(inti=0;i<heightsSize;i++){ans[i]=(char*)malloc(sizeof(char)*namesSize);ans[i]=names[ret[i][1]];}// 释放临时数组for(inti=0;i<heightsSize;i++){free(ret[i]);}free(ret);returnans;}(2)运用strcpy函数:
/** * Note: The returned array must be malloced, assume caller calls free(). */#defineunlikely(x)__builtin_expect(!!(x),0)intcmp(constvoid*a,constvoid*b){int*rwna=(*(int**)a);int*rwnb=(*(int**)b);returnrwnb[0]-rwna[0];//降序排列}char**sortPeople(char**names,intnamesSize,int*heights,intheightsSize,int*returnSize){*returnSize=0;//分配空间来存储,第一个储存升高,第二个存储下标int**ret=(int**)malloc(sizeof(int*)*heightsSize);if(unlikely(!ret)){returnNULL;}for(inti=0;i<heightsSize;i++){ret[i]=(int*)malloc(sizeof(int)*2);if(unlikely(!ret[i])){for(intk=0;k<=(*returnSize);k++){free(ret[k]);}free(ret);returnNULL;}ret[i][0]=heights[i];ret[i][1]=i;(*returnSize)++;}//二维数组排序qsort(ret,heightsSize,sizeof(int*),cmp);char**ans=(char**)malloc(sizeof(char*)*heightsSize);if(unlikely(!ans)){returnNULL;}// for(int i=0;i<heightsSize;i++)// {// ans[i]=(char *)malloc(sizeof(char)*namesSize);// ans[i]=names[ret[i][1]];// }// return ans;for(inti=0;i<heightsSize;i++){// 复制字符串而不是直接赋值指针ans[i]=(char*)malloc(strlen(names[ret[i][1]])+1);if(unlikely(!ans[i])){// 释放已分配的内存for(intj=0;j<i;j++){free(ans[j]);}free(ans);for(intk=0;k<heightsSize;k++){free(ret[k]);}free(ret);returnNULL;}strcpy(ans[i],names[ret[i][1]]);}// 释放临时数组for(inti=0;i<heightsSize;i++){free(ret[i]);}free(ret);returnans;}