tPeca* criarPecas(FILE *pFile, int tam){
int i = 0,linhaV,colunaV,j = 0;
char ***elemento = (char***)malloc(tam*sizeof(char**));;
tPeca *pecaJogo = (tPeca*)malloc(tam*sizeof(tPeca));
if(pecaJogo==NULL)
return NULL;
for(i=0;i<tam;i++){
j=0;
fscanf (pFile, "%[^;]", pecaJogo[i].nome);
fscanf (pFile, ";%d", &pecaJogo[i].qtd);
fscanf (pFile, ";%d", &linhaV);
pecaJogo[i].linha = linhaV;
fscanf (pFile, ";%d", &colunaV);
pecaJogo[i].coluna = colunaV;
**elemento[i] = (char**)malloc(linhaV * sizeof(char*));
*elemento[i][j] = (char*)malloc(colunaV * sizeof(char));
j++;
}
return pecaJogo;
}
*** elemento是matriz的指针,我认为我对malloc有问题...我收到了分段错误
答案 0 :(得分:1)
这两个陈述是我猜你遇到问题的地方:
**elemento[i] = (char**)malloc(linhaV * sizeof(char*));
*elemento[i][j] = (char*)malloc(colunaV * sizeof(char));
您在上面创建了char ***,并尝试创建一个指针数组:
char ***elemento = (char***)malloc(tam*sizeof(char**));;
应该是:
//this step creates an array of pointers
char ***elemento = malloc(tam*sizeof(char*));
//Note: there is no need to cast the return of [m][c][re]alloc in C
// The rules are different in C++ however.
现在,您可以将elemento放入循环中,为您创建的每个指针分配指针空间:
//this step creates an array pointers for each element of the array created above:
for(i=0;i<tam;i++) //assuming size is also tam (you specified nothing else)
{
elemento[i] = malloc(tam*sizeof(char *));//each ith element will
//now have tam elements of its own.
}
接下来,在每个位置分配内存:
for(i=0;i<tam;i++)
{
for(j=0;j<tam;j++)
{
elemento[i][j] = malloc(someValue*sizeof(char));
//Note: sizeof(char) == 1, so could be:
//elemento[i][j] = malloc(someValue);
}
}
现在你有一个完全分配的3D阵列。
全部放在一起,(一个简单的2D示例)
为多维数组创建内存时,必须创建 指针数组 ,和 内存的组合 。对于2D示例(可能用于字符串数组),您可以这样做:
char ** allocMemory(char ** a, int numStrings, int maxStrLen)
{
int i;
a = calloc(sizeof(char*)*(numStrings), sizeof(char*));//create array of pointers
for(i=0;i<numStrings; i++)
{
a[i] = calloc(sizeof(char)*maxStrLen + 1, sizeof(char));//create memory at each location
}
return a;
}
您还必须创建释放内存的方法:
void freeMemory(char ** a, int numStrings)
{
int i;
for(i=0;i<numStrings; i++)
if(a[i]) free(a[i]);
free(a);
}
用法:
char **array = {0};
...
array = allocMemory(array, 10, 80);
...
freeMemory(array, 10);
将创建内存,并且地址足以包含10个80个字符串的数组(char数组),然后释放它。
可以通过添加指针创建的另一个图层(for循环)将其扩展为3D,如帖子顶部所示。在此实现中,最内层循环始终为您创建的每个地址位置创建实际内存。