【问题标题】:What is the compatible pointer type when I pass it as a reference of a pointer to a function that goes through another function in C?当我将它作为指向通过 C 中另一个函数的函数的指针的引用传递时,兼容的指针类型是什么?
【发布时间】:2015-09-21 18:07:20
【问题描述】:

我知道,为了让调用者的内存反映被调用者本地参数的变化,你需要将参数作为指针的引用传递。当我直接使用Push(1, &h1); Push(3, &h1); Push(5, &h1); 时,会创建并打印一个正确的列表。但是如果我通过createList(&h1); 调用Push(..., &h1),编译器会给出 warning: incompatible pointer types passing 'struct ListNode ***' to parameter of type 'struct ListNode **'; remove & [-Wincompatible-pointer-types],并且没有创建列表。在我按照编译器所说的去做之后 - 删除了 &,我仍然没有得到任何列表。

我的问题:当我将它作为指向通过 C 中另一个函数的函数的指针的引用传递时,兼容的指针类型是什么?

void Push(int val, struct ListNode **headRef){
  struct ListNode *newNode = malloc(sizeof(struct ListNode));

  newNode->val = val;
  newNode->next = *headRef;
  *headRef = newNode;
}

void createList(struct ListNode **head){
  int num;

  printf("Enter data to create a list. (Enter -1 to end)\n");
  scanf("%d", &num);

  while (num != -1){ 
    Push(num, &head); // Note: the '&'
    scanf("%d", &num);
  }
}

int main(){
  createList(&h1);
  printList(h1);
}

void printList(struct ListNode *head){
  struct ListNode *curr= head;

  while (curr != NULL) {
    printf("%d ", curr->val);    
    curr = curr->next;
  }
}

【问题讨论】:

  • C 中没有“引用”。只有指针。
  • 看你createList的声明;它需要指向ListNode 的指针的地址。现在看看Push。它期待同样的事情。那么,当您已经拥有Push 的需求时,为什么还要用&head 调用Push 呢? (即head)。
  • @CareyGregory,不,鉴于提供的函数签名(对我来说看起来不错),如果 createList(&h) 是类型正确的,那么 Push(1, &h) 也是。
  • @JohnBollinger 函数签名没有问题,但 &headListNode ***,而不是 ListNode **。因此发出警告。
  • @CareyGregory,是的,你是对的。我需要更仔细地阅读代码。我的意思是,如果createList(&h) 是正确的,那么Push(1, &h) 当从同一范围调用时 也必须是正确的。我错过了来自createList() 内部的电话。

标签: c pointers reference linked-list pass-by-reference


【解决方案1】:

当您在createList 中调用Push 时,您需要传递head,而不是&head

Push 需要 ListNode **createList 中的head 变量也是ListNode ** 类型,因此在调用Push 时无需获取其地址或取消引用它。

createList 中,head 包含h1 的地址。如果将相同的值传递给Push,那么在该函数中headRef 也包含h1 的地址。

我用Push(num, head); 运行了你的代码,它似乎输出了你所期望的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多