我想传递一个指向函数的指针,该函数将调用第二个使用 realloc 的函数。 问题是 realloc 返回 NULL。
不知道是函数调用中*的个数有误还是别的什么地方。
你能帮帮我吗?
代码:
int main(){
// some code.
clause_t* ptr; //clause_t is a structure i declared.
//Some work including the initial allocation of ptr (which is working).
assignLonely(matSAT, ic.nbClause, ic.nbVar, ptr); //the issue is here.
//Some other work
}
void assignLonely(int** matSAT, int nbClause, int nbVar, clause_t* ptr)
{
int i = 0, j = 0;
int cpt = 0;
int indice = -1;
for (i = 0; i < nbClause ; ++i)
{
j = 0;
cpt = 0;
while((j < nbVar) && (cpt < 2))
{
if (matSAT[i][j] != 0)
{
cpt++;
}
else
{
indice = j;
}
if (cpt < 2)
{
deleteClause(indice, &ptr);
}
j++;
}
}
}
void deleteClause(int indiceClause, clause_t** ptr)
{
int i = indiceClause;
int nbElt = sizeof((*ptr))/sizeof((*ptr)[0]);
int tailleElt = sizeof((*ptr)[0]);
while(i+1 < nbElt)
{
(*ptr)[i] = (*ptr)[i+1];
i++;
}
*ptr = (clause_t*)realloc(*ptr, (nbElt-1)*tailleElt);
if (*ptr == NULL)
{
fprintf(stderr, "Erreur reallocation\n");
exit(EXIT_FAILURE);
}
}
最佳答案
你必须声明函数 assignLonely
类似于函数 deleteClause
void assignLonely(int** matSAT, int nbClause, int nbVar, clause_t** ptr);
如果您希望将函数中 ptr 的更改存储在 main 中的原始对象中。
还要考虑到这个声明
int nbElt = sizeof((*ptr))/sizeof((*ptr)[0]);
错了。
表达式 sizeof((*ptr))
将返回指针的大小。指针不保留有关它们指向的数组中有多少元素的信息。
所以表达
(nbElt-1)
可以为零甚至为负数。
关于c++ - 将指针传递给函数并使用 realloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27593351/