gpt4 book ai didi

c - 当传递结构体地址时,我无法更改C中实际参数的值

转载 作者:行者123 更新时间:2023-11-30 15:55:00 25 4
gpt4 key购买 nike

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

typedef struct s{
int n;
}F;

F* make();
void create(F *s);
void add(F *f);
void show(F *f);

int main()
{
F *f=NULL;

//1.) the following doesn't work
create(f);
show(f);


//2.) The Following is work
f=make();
show(f);



printf("Hello world!\n");
return 0;
}

void add(F *f){
(f->n)++;
}
void show(F *f){
printf("\n======\n %d \n======\n",f->n);
}
F* make(){
F * temp=(F*)malloc(sizeof(F));
temp->n=19;
return temp;
}
void create(F *s){
F * temp=(F*)malloc(sizeof(F));
temp=make();
s=temp;
show(s);
}

请解释一下为什么代码片段(1)显示碎片错误(我知道这是关于访问无效的内存空间,但通过查看我自己的代码,我不知道错误在哪里。),但是(2) 还好,工作正常。预先感谢您。

最佳答案

出现段错误的原因是 main 中的变量 f 仍为 NULL

那是因为在 create() 中,您将 temp 分配给局部变量 s,这与 f< 无关 函数之外。如果您希望函数修改指针指向的位置,则需要将指针传递给指针,即。 F **s

您的 create() 函数可能类似于:

void create(F **s){
F * temp=(F*)malloc(sizeof(F));
temp=make();
*s=temp;
show(*s);
}

您将把 f 的地址传递给 create():

create(&f);

s包含f的地址,因此修改*s的值与修改f的值相同.

关于c - 当传递结构体地址时,我无法更改C中实际参数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12600117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com