0
#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)没关系,它工作正常。先感谢您 。

4

3 回答 3

1

你得到一个段错误的原因是因为变量finmain是剩余的NULL

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

你的create()函数可能看起来像:

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

你会将地址传递fcreate()

create(&f);

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

于 2012-09-26T10:59:34.923 回答
0

您需要更改create()以接受指向这样的指针的指针F

void create(F** s)
{
    F* temp = malloc(sizeof(F));
    *s = temp;
    show(*s);
}
于 2012-09-26T10:57:42.230 回答
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); 
}
于 2012-09-26T10:57:48.850 回答