gpt4 book ai didi

c - C 中矩阵的指针

转载 作者:行者123 更新时间:2023-11-30 15:19:02 27 4
gpt4 key购买 nike

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 是矩阵的指针,我认为我的 malloc 有问题...我收到了段错误

最佳答案

这两个陈述是我猜您遇到问题的地方:

**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 个字符串的数组(字符数组)的地址,然后释放它。

这可以通过添加指针创建的另一层(for 循环)扩展到 3D,如帖子顶部所示)。在此实现中,最内层循环始终为您创建的每个地址位置创建实际内存。

关于c - C 中矩阵的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30893749/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com