#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;
}
求解答呀,會出現段錯誤
額,這類程序非常有意思,能強化存意識~
我覺得至少存在兩點問題:
(1)如樓上所言,“不滿足數組要求的連續性的基本條件”,或者說這裡是三級指針,意味著內存四級存儲空間,級與級之間是不一定連續的,級內是連續的(從虛擬地址來說)~所以你無法用數組 pArr[i][j][k]方式訪問~
(2) char pArr;你定義在了函數char Create3DActiveArray(int x, int y, int z)內,是局部變量,存放在堆棧上,函數調用結束後內存會銷毀~所以函數返回值無效。你可以傳char **table地址過去(如我修改的代碼),也可以char **table定義在main函數外作為全局變量。
#include
#include
#include
void Create3DActiveArray(char**** pArr,int x, int y, int z)
{
// char **pArr;
char **pArr3Temp;//二級指針數組指針游標
char ** pArr2Temp;//一級指針數組指針游標
char * pArr1Temp;//字符數組指針游標
int i, j,k;
*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;
}
我修改了你的void Create3DActiveArray(char**** pArr,int x, int y, int z)函數和main()函數,你按這個思路修改void Free3DActiveArray(char ***pArr, int x, int y)函數吧~