【问题标题】:passing pointer to function and using realloc将指针传递给函数并使用 realloc
【发布时间】:2015-02-20 00:01:38
【问题描述】:

我想传递一个指向函数的指针,该函数将调用第二个使用 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);
}

}

【问题讨论】:

  • int nbElt = sizeof((*ptr))/sizeof((*ptr)[0]); 这并不像你想象的那样。 *ptr 只是另一个指针,而不是数组。所以这将是 1 或 0,具体取决于 sizeof 子句_t。而且您的 realloc 将是零字节,这就是它返回 null 的原因。一个调试器或一些 printfs(例如nElt)会向您展示这一点,并且在询问之前也是一个好主意
  • 请选择语言标签 - C 和 C++ 不同。 (大概去掉C++标签)
  • 您需要#include &lt;stdlib.h&gt; 以确保realloc 正常运行

标签: c++ c pointers malloc realloc


【解决方案1】:

你必须声明函数assignLonely类似于函数deleteClauselike

void assignLonely(int** matSAT, int nbClause, int nbVar, clause_t** ptr);

如果您希望函数中 ptr 的更改将存储在 main 中的原始对象中。

还要考虑到这个声明

int nbElt = sizeof((*ptr))/sizeof((*ptr)[0]);

错了。 表达式sizeof((*ptr)) 将返回指针的大小。指针不保存有关它们指向的数组中有多少元素的信息。

所以表达

(nbElt-1)

可以等于0甚至是负数。

【讨论】:

  • 好的,但这不是 realloc 返回 null 的原因
  • 谢谢大家,但我已经在这里使用了类似的东西: void initMatSAT(int** matSAT) { int nbRow = sizeof(matSAT)/sizeof(matSAT[0]); int nbColumn = sizeof(matSAT[0])/sizeof(matSAT[0][0]); //剩下的工作。它奏效了。
  • @user3564164 matSAT 的类型是 int ** 所以它的大小是 4 字节或 8 字节,具体取决于编译程序的环境。 matSAT[0] 具有 int * 类型,即它也是一个指针。因此 sizeof( matSAT ) / sizeof( matSAT[0] ) 的结果将始终等于 1。
  • @user3564164,打印 nEblt。你会看到的。 C 中的指针只是不会跟踪它们所指向的内容,无论您以前认为什么“有效”。
  • 你说得对,保罗,我刚刚尝试了一些 printfs,它打印了 1,就像你刚才说的那样。所以,如果我理解,我将不得不将我的数组的维度传递给我的函数,而不是尝试用 sizeof() 来计算它们?问题是,我只是想了解它在哪里工作得很好和哪里不工作之间的区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
相关资源
最近更新 更多