【发布时间】: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 函数签名没有问题,但
&head是ListNode ***,而不是ListNode **。因此发出警告。 -
@CareyGregory,是的,你是对的。我需要更仔细地阅读代码。我的意思是,如果
createList(&h)是正确的,那么Push(1, &h)当从同一范围调用时 也必须是正确的。我错过了来自createList()内部的电话。
标签: c pointers reference linked-list pass-by-reference