在下面的代码中,我可以从函数中修改 main 中使用的变量。
#include<stdio.h>
int main()
{
int *a,b=10;
a = &b;
printf("%d\n",*a);
ref(a);
printf("%d\n",*a);
return 1;
}
int ref(int *a)
{
int b = 98;
*a = b;
return 1;
}
然而,在下面的代码中,我无法做到同样的事情。
我知道我们可以通过使用双指针从函数中修改 main 中的值。我也知道我们可以使用单指针进行修改,方法是将所需地址返回给 main 并在 main 中以相同的数据类型获取它。我只是想知道我是否可以通过将它作为参数传递给函数来修改 main 中的值,仅作为指向(结构)变量的单个指针。
注意:我用注释“//WC”表示工作代码。如果有人能对我进行同样的解释,我将不胜感激。
//int insert(int data, Node **head) //WC
int insert(int data, Node *head)
{
Node *temp, *run;
temp = (Node *) malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
//if(*head == NULL) //WC
if(head == NULL)
{
printf("1st node\n");
//*head = temp; //WC
*head = *temp;
}
else
{
printf("node after first\n");
//run = *head //WC
*run = *head;
while(run->next != NULL)
{
run = run->next;
}
run->next = temp;
}
return 1;
}
int main()
{
Node *head;
insert(10, head);
insert(20, head);
insert(30, head);
insert(40, head);
insert(50, head);
return 1;
}
最佳答案
How can I pass a single pointer to a structure, inside a function and modify that structure variable?
TL;DR:您可以修改指针指向的值,但不能修改传递的指针本身。
C
使用按值传递函数参数传递。您不能更改从被调用函数接收到的参数的值,并期望它反射(reflect)在用作调用函数参数的变量中。
但是,对于指针,您通常不会修改指针本身,而是修改它指向的值。因此,该指针指向的更改值将反射(reflect)在调用函数中。
关于c - 如何在函数内部将单个指针传递给结构并修改该结构变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31163462/