【问题标题】:Moving pointers memory allocation from main() to function and using pointer in other functions将指针内存分配从 main() 移动到函数并在其他函数中使用指针
【发布时间】:2015-03-17 17:02:17
【问题描述】:

嘿,我正在尝试将指针内存分配 d =(deque*)malloc(sizeof(deque)); 移动到名为 void initDeque() 的第一个函数中。我尝试在main 中保留声明并在函数中分配内存,但程序在初始化双端队列后就崩溃了,我无法在其他函数中使用指针。

代码如下:

int main(){
    int x;
    deque *d;
    d = (deque*)malloc(sizeof(deque));

    initDeque(d);
    putFront(d,10);

以及我想为指针移动内存分配的函数:

void initDeque(deque *d){ //Create new deque
    //d = (deque*)malloc(sizeof(deque));
    printf("Initializing deque\n");
    d->front=NULL;
    d->rear=NULL;
}

如果声明和分配在main() 中,程序运行良好,但是当我将分配放入void initDeque 时它会崩溃。

【问题讨论】:

标签: c pointers memory


【解决方案1】:

参数(偶数指针)在 C 中是 passed by value

所以返回指针:

deque *make_queue(){ //Create new deque
  deque *d = malloc(sizeof(deque));
  if (!d) { perror("malloc"); exit(EXIT_FAILURE); };
  printf("Initializing deque\n");
  d->front=NULL;
  d->rear=NULL;
  return d;
}

并在您的main 开头调用d = make_queue();;在进行malloc总是测试失败

或者,传递一个指针的地址,如answered by clcto

阅读C dynamic memory management 上的维基页面。不要忘记适当地致电free。对于调试,如果可用,请使用 valgrind。避免memory leaks(和双倍free-s)。当你的 C 语言比较成熟时,请阅读garbage collection 上的维基页面,或许在某些情况下考虑使用Boehm conservative garbage collector

【讨论】:

    【解决方案2】:

    一种解决方案是给指针传递一个指针:

    int main()
    {
        deque *d;
        initDeque( &d );
    }
    
    void initDeque( deque **d )
    {
        *d = malloc( sizeof( deque ) );
    }
    

    【讨论】:

      【解决方案3】:

      调用函数时,您将 d 变量中的值作为参数发送给函数,而不是其指针(也称为内存地址)。

      initDeque(d);
      

      为了发送指针本身,您必须发送它的内存地址:

      initDeque(&d);
      

      为此,我还建议您使用指针中的指针,这样即使您尚未使用 memalloc,您也可以发送假装分配数据的地址。

      如果您尝试显示 &d 的值,它将是一个内存地址,因此请确保稍后记住它的指针。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-13
        • 2015-07-18
        • 1970-01-01
        • 2018-08-24
        • 2015-04-27
        • 1970-01-01
        • 2014-06-03
        • 1970-01-01
        相关资源
        最近更新 更多