【问题标题】:What do I need to put before the ampersand?我需要在&符号之前放什么?
【发布时间】:2014-04-10 03:21:37
【问题描述】:

extractMin 的参数行出现以下错误:

randmst.c:129: 错误:在“&”标记之前需要“;”、“,”或“)”

如果我没有粘贴足够的代码以使错误变得明显,请告诉我。

//the heap functions

//based on p. 163 of clrs
VertexPointer
extractMin(VertexPointer *heap, int &heap_size){
    VertexPointer max = heap[0];
    (*heap[0]).key = 100;
    heap_size = heap_size - 1;
    minHeapify(heap, heap_size, 1);
    return max;
}

【问题讨论】:

  • C 中没有引用。
  • &token表示变量的地址,函数参数要改成*heap_size[表示它保存了变量的地址]

标签: c pointers arguments ampersand


【解决方案1】:

您不能在 C 中执行此操作 extractMin(VertexPointer *heap, int &heap_size) - 将其更改为 extractMin(VertexPointer *heap, int *heap_size)

C 中没有传递引用。所以你应该有这样的东西:

extractMin(VertexPointer *heap, int *heap_size){
    VertexPointer max = heap[0];
    (*heap[0]).key = 100;
    *heap_size = *heap_size - 1;
    minHeapify(heap, *heap_size, 1); 
    return max;
}

& 用于获取变量的地址,所以在调用函数时应该这样调用它:

extractMin(someAddress_to_heap, someAddress_to_heap_size)

【讨论】:

  • 漂亮。确保你注意到他在函数中取消引用heap_size。当您调用extractMin 时,您必须将& 地址运算符应用于heap_size 参数。
【解决方案2】:

通过引用传递在 C 中不起作用,通过引用传递和通过地址传递是有区别的。 C++ 支持通过引用传递,但 C 不支持。 将代码更改为

VertexPointer
extractMin(VertexPointer *heap, int *heap_size)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-22
    • 2020-06-15
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 2015-08-19
    相关资源
    最近更新 更多