为什么我的初始化函数返回null? [英] Why is my initialization function returning null?

查看:72
本文介绍了为什么我的初始化函数返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次用C语言编写程序.我在C ++方面有丰富的经验,但是C对指针的依赖以及newdelete的缺失确实让我失望.我定义了一个简单的数据结构,并编写了一个将其初始化的函数(通过获取指针).这是我的代码:

I'm writing a program in C for the first time. I have a good bit of experience with C++, but C's reliance on pointers and the absence of new and delete are really throwing me off. I defined a simple data structure, and wrote a function that will initialize it (by taking a pointer). Here's my code:

//in Foo.h
#include <stdio.h>
#include <stdlib.h>

typedef struct Foo {
    struct Foo * members[25] ;
} Foo ;

void foo_init(Foo * f) ;
void foo_destroy(Foo * f) ;


//in Foo.c
void foo_init(Foo * f) {
    f = (Foo*)malloc(sizeof(Foo));

    for (size_t i = 0 ; i < 25 ; i++) {
        f->members[i] = NULL ;
    }
}

//define foo_destroy()

//in main.c
#include "Foo.h"

int main(int argc, const char * argv[])
{

    Foo * f ;
    foo_init(f) ;
    /* why is f still NULL here? */

    foo_destroy(f) ;

    /* ... */
    return 0;
}

当我在f上测试我的foo_init()函数(指向Foo结构的指针)时,该函数返回后为null.但是,指针f inside foo_init()初始化就很好,因此,我认为这与init函数本身无关.在黑暗中拍摄,但这可能与C处理值传递/引用传递的方式有关(我仍然不完全了解这一点)?我该如何纠正?

When I tested my foo_init() function on f (pointer to a Foo struct), it was null after the function returned. The pointer f inside foo_init() is initialized just fine, however, so I don't think this is a problem with the init function itself. Shot in the dark, but could this be related to the way C handles passing by value/passing by reference (something I still don't entirely have a grasp on)? How can I correct this?

推荐答案

void foo_init(Foo* f)

在C中,参数按值传递.在这里,您将传递一个名为f且类型为Foo*的参数.在功能中,您分配给f.但是由于参数是通过值传递的,因此您将分配给该函数专用的本地副本.

In C parameters are passed by value. Here you pass a parameter named f, of type Foo*. In the function you assign to f. But since the parameter is passed by value, you are assigning to the local copy, private to that function.

为了让调用者看到新分配的结构,您需要额外的间接访问级别:

In order for the caller to see the newly allocated struct, you need an extra level of indirection:

void foo_init(Foo** f)
{
    *f = ...;
}

在呼叫站点:

Foo* f;
foo_init(&f);

现在,由于您的函数旨在将新值发送给调用方,并且您的函数当前具有void返回值,因此将新值返回给调用方会更有意义.像这样:

Now, since your function is designed to send a new value to the caller, and your function currently has void return value, it would make more sense to return the new value to the caller. Like this:

Foo* foo_init(void)
{
    Foo* foo = ...;
    return foo;
}

您将这样称呼:

Foo* f = foo_init();

这篇关于为什么我的初始化函数返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆