三级指针四级存储空间
2015-05-15 青岛 张俊浩
今天在技术问答板块看到的帖子,花时间调出来,也顺便整理作为笔记~
原帖是:
#include<stdio.h> #include<stdlib.h> #include<string.h> char*** Create3DActiveArray(int x, int y, int z) { char ***pArr; int i, j,k; pArr = (char ***)malloc(x * sizeof(char **)); for (i = 0; i < x; i++) { pArr[i] = (char **)malloc(y * sizeof(char *)); for (j = 2; j < y; j++) { pArr[i][j] = (char *)malloc(z * sizeof(char)); for (k = 0; k < z; k++) { pArr[i][j][k] = 0; } } } return pArr; } void Free3DActiveArray(char ***pArr, int x, int y) { int i, j, k; for (i = 0; i < x; i++) { for (j = 0; j < y; j++) { free(pArr[i][j]); pArr[i][j] = NULL; } free(pArr[i]); pArr[i] = NULL; } free(pArr); } int main(){ char ***table=Create3DActiveArray(2,2,100); strcpy(table[0][0],"num"); printf("%s",table[0][0]); return 0; } //求解答呀,会出现段错误
额,感觉这类程序非常有意思,能强化内存意识~这里是三级指针,意味着内存四级存储空间,级与级之间不一定是连续的,级内是连续的(从虚拟地址来说)~所以你无法用pArrp[i][j][k]访问方式~
附上内存分布图和修改的部分代码~
#include<stdio.h> #include<stdlib.h> #include<string.h> void Create3DActiveArray(char**** pArr,int x, int y, int z) { // char ***pArr; char ***pArr3Temp;//二级指针数组指针游标 char ** pArr2Temp;//一级指针数组指针游标 char * pArr1Temp;//字符数组指针游标 <span style="white-space:pre"> </span>int i, j,k; <span style="white-space:pre"> </span>*pArr = (char ***)malloc(x * sizeof(char **)); pArr3Temp =*pArr; for (i = 0; i < x; i++) { // pArr1Temp = *pArr2Temp; *pArr3Temp = (char **)malloc(y * sizeof(char *)); pArr2Temp = *pArr3Temp; for (j = 0; j < y; j++)//之前写j=2?why? { *pArr2Temp = (char *)malloc(z * sizeof(char)); pArr1Temp = *pArr2Temp; for (k = 0; k < z; k++) { *pArr1Temp = 0; ++pArr1Temp;//遍历字符指针数组 } ++pArr2Temp;//遍历一级指针数组 } ++pArr3Temp;//遍历二级指针数组 } // return pArr; } int main(){ char ***table; Create3DActiveArray(&table,2,2,4); strcpy((*(*table)),"num"); printf("%s\n",*(*table)); return 0; }
时间: 2024-10-12 16:00:40