C 如何在函数内部传递一个指向结构的指针并修改该结构变量?
在下面的代码中,我可以从函数中修改main中使用的a变量C 如何在函数内部传递一个指向结构的指针并修改该结构变量?,c,pointers,structure,singly-linked-list,C,Pointers,Structure,Singly Linked List,在下面的代码中,我可以从函数中修改main中使用的a变量 #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;
#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;
}
如何在函数内部传递一个指向结构的指针并修改该结构变量
TL;DR:您可以修改指针指向的值,但不能修改传递的指针本身
C
使用传递值传递函数参数。您不能更改从被调用函数接收的参数的值,并期望它反映在用作调用函数参数的变量中
但是,对于指针,通常不修改指针本身,而是修改它指向的值。因此,该指针指向的更改值将反映在调用函数中。当您检查head是否为空(具有NULL值)时,您需要检查head(*head)的内容,而不是head本身,因为这意味着它自己的地址。所以如果(head==NULL),应该是*head==NULL。head表示指针头的内存地址,*head表示该地址中保存的内容(指向的内容)。根据这个逻辑,*头=温度;是正确的,因为它将在head中保存动态分配的内存地址-temp的地址,但是后面的(*head=*temp)将尝试将temp的内容复制/保存到head,这是没有意义的,因为head只有指针的大小,并且无论节点大小如何,都可以分配temp。我希望我至少帮了一点忙,下面是您代码的工作版本:)
#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;
}
(编辑:使用多个指针可能会使读取复杂化,因此我宁愿使用以下结构定义)
在更高版本中,
if(head==NULL){*head=*temp;}
将执行segfault。使用单个*
可以修改参数指向的内容,但不能修改指针本身。此时您需要双**
,然后您可以同时修改这两个选项。使用单星,如果您想修改它,您必须(如您所说)从函数返回一个新的指针值代码>也调用未定义的行为<代码>运行不确定。坚持你所知道的任何一种工作方式。是的,我知道我的代码是不可执行的,我无法使它可执行。这就是我贴出这个问题的原因@SouravGhosh@Denise你没有明白我的意思。我想,你实际上是想写head=temp
,不是吗?不需要取消引用。你的意思是我可以修改head而不是*head?是你编译的吗??它将抛出以下不兼容类型错误,*head=temp
和run=*head
和对于*head==NULL
的二进制操作数无效==
您可以将结构定义发布到这里(节点)吗?我刚刚编辑过它,我的错误:)*head应该是**head,因为参数中的*head是第一个节点的地址,而**head是指向第一个节点的指针的地址。正如我已经说过的,我知道使用双指针进行相同操作的方法。我所需要的是,我可以在函数中更改我的*var,并使它在int数据类型的情况下反映在main中。我不知道如果是一个结构,我该怎么做。如果可以的话,请帮助我@Lukas。无论如何,谢谢你到现在为止的解释。
int insert(int data, Node **head) //WC, This is correct because the parameter **head takes address of the pointer to the first node if any.
//int insert(int data, Node *head)
{
Node *temp, *run;
temp = (Node *) malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
if(*head == NULL) //WC, checking if head has any address value inside (not its own address)
{
printf("1st node\n");
*head = temp; //WC, because temp has address of the allocated memory and you wanna hold that address as the head / first node.
}
else
{
printf("node after first\n");
run = *head //WC
//*run = *head; you can't use this, one reason is because head could point to any size of memory (e.g 10000kb) and run has a size of a pointer, just few bytes.
while(run->next != NULL)
{
run = run->next;
}
run->next = temp;
}
return 1;
}
typedef struct node* PNode; //Pointer to node
typedef struct node {
int item;
Pnode next;
} Node;
void insert(int data, PNode *head) {
PNode temp, run = *head;
temp = (PNode)malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
if (run == NULL){
*head = temp;
}//first node
else{
while (1) {
if (run->next == NULL) {
run->next = temp;
break;
}
run = run->next;
}
}
}