【问题标题】:Passing typedef structure as call by reference in C将 typedef 结构作为 C 中的引用调用传递
【发布时间】:2014-07-07 04:49:58
【问题描述】:

我正在尝试用 C 创建一个链表,我的代码如下。

#include <stdio.h>
#include <stdlib.h>


typedef struct node {
    int data;
    struct node *next;
}node_t;


void insert_into_list(node_t *,int);
void print_list(node_t *);
node_t *create_node(int );



void insert_into_list(node_t *head, int value){
    node_t *temp ;
    temp = create_node(value);
    if(head == NULL){
        printf("Inserting node for the first time\n");
        head = temp;
    }else {
        head->next = temp;
    }

}
void print_list(node_t *head){
    node_t *current = head;
    while(current!=NULL){
        printf("%d----->",current->data);
        current = current->next;
    }
    printf("NULL");
}
node_t *create_node(int value){
    node_t *new_node = malloc(sizeof(node_t));
    if(new_node==NULL){
        printf("Memory allocation failed for the list creation. :(");
        return NULL;
    }
    new_node->data = value;
    new_node->next = NULL;
    return new_node;
}


int main(int argc, char *argv[]) {
    node_t *head = NULL;
    insert_into_list(head,10);
    if(head==NULL){
        printf("Still head is NULL :(");
    }else{
        printf("Head is not NULL:)");
    }
    print_list(head);
    return 0;
}

main 中,我正在调用 insert_into_list,即使在成功分配内存后,我也无法使用新创建的节点获取 head 值。仍将值显示为 NULL。

我用 gdb 调试过,发现到下面的代码,head 不是 NULL

printf("Inserting node for the first time\n");
head = temp;

我以为我是通过引用传递并期望值反映在调用者函数中。

请纠正我。

【问题讨论】:

  • 从技术上讲,您正在传递一个指针。虽然“通过引用”可以应用于此,但通常不是为了避免与 C++ 中的引用传递混淆(这是不同的)。
  • C 中没有“按引用传递”。如果要初始化指针值本身,则需要将指针的地址向下传递给函数。
  • 您正在传递 head 指向“通过引用”的实际节点结构 - 您没有“通过引用”传递 head 指针。把函数改成void insert_into_list(node_t **,int);,用insert_into_list(&amp;head,10);调用

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


【解决方案1】:

如果你想在 C 中通过引用(或者更确切地说,等价物)传递,你必须传递一个指针。要通过引用传递指针,您必须将指针传递给指针。

所以在例如insert_into_list 你必须将head 声明为指向指针的指针:

void insert_into_list(node_t **head, int value)

并在访问head 变量时使用解引用运算符。

您使用地址运算符&amp; 调用它:

node_t *head = NULL;
insert_into_list(&head,10);

【讨论】:

  • 为了完整性:如果按照此答案提出建议,则在 insert_into_list() 内将 head 替换为 (*head)
  • 感谢 Joachim 和 alk :)
猜你喜欢
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 2021-08-19
  • 2018-04-26
  • 1970-01-01
  • 2013-05-12
相关资源
最近更新 更多