传递结构到c语言中的函数

问题描述 投票:0回答:1

有人能帮忙吗?为什么在这个程序中调用函数时不需要“&”?但被认为在引用调用中需要'&'。

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


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


void traversal(struct node *ptr)
{
while(ptr!=NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}
}


int main()
{
struct node *head;
struct node *second;
struct node *third;

head = (struct node*) malloc(sizeof(struct node));
second = (struct node*) malloc(sizeof(struct node));
third = (struct node*) malloc(sizeof(struct node));

head->data = 7;
head->next = second;

second->data = 5;
second->next = third;

third->data = 12;
third->next = NULL;

traversal(head);

return 0;
}

有人能帮忙吗?为什么在这个程序中调用函数时不需要“&”?但被认为在引用调用中需要'&'。

c function pointers data-structures structure
1个回答
0
投票

你有一个单向链表,其中节点由指针链接。

遍历函数不接受结构节点类型的对象。它接受一个指向结构节点类型对象的指针。

void traversal(struct node *ptr)
{
while(ptr!=NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}
}

由于用作参数表达式的原始指针在函数内没有改变,因此通过指向它的指针通过引用将其传递给函数没有任何意义。

© www.soinside.com 2019 - 2024. All rights reserved.