#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)没关系,工作正常。提前谢谢。
答案 0 :(得分:1)
您遇到seg错误的原因是因为f
中的变量main
仍然是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
的值相同。
答案 1 :(得分:0)
您需要更改create()
以接受指向F
的指针,如下所示:
void create(F** s)
{
F* temp = malloc(sizeof(F));
*s = temp;
show(*s);
}
答案 2 :(得分:0)
F *f=NULL; //1.) the following doesn't work
create(f);
将指针 按值 传递给该函数。原始指针f
永远不会分配任何内存。该函数将内存分配给指针f
的副本。虽然f
仍然指向NULL
。最后,您最终取消引用导致 未定义行为 的NULL
指针,这会以分段错误的形式显示。
您需要将指针 通过引用 传递给函数以分配内存:
create(&f);
其中:
void create(F **s);
void create(F **s)
{
*s = malloc(sizeof(F));
show(*s);
}