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

时间:2012-09-26 10:54:29

标签: c malloc

#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)没关系,工作正常。提前谢谢。

3 个答案:

答案 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); 
}