结构初始化不使用malloc工作 [英] Structure initialization does not work with malloc

查看:246
本文介绍了结构初始化不使用malloc工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在C小的背景下,我想挖了,我遇到了一些我无法解释。

I've a small background in C that I'm trying to dig up, and I encountered something I can't explain.

让我们说我有以下结构:

Let's say I have the following structure:

struct World {
   Things* things;
};

和功能如下:

void initWorld(World *world);

void addThingToWorld(World *world, Thing *thing);

现在,根据 initWorld 的实施以及如何我使用它,它会工作或没有。但我不明白,为什么第二次执行应该失败。这两种实现方式如下:

Now, depending on the implementation of initWorld and how I use it, it will either work or not. But I don't understand why the second implementation should fail. Both implementations are below:

void initWorld(World *world){
    world->things = NULL;
}

// usage
World world;
initWorld(&world);
// will work, because world has been correctly initialized.
addThingToWorld(&world, &something);

二(失败)执行

void initWorld(World *world){
    world = (World*) malloc(sizeof(World));
    world->things = NULL; // here it does not work! things is not changed to 0x0 :(
}

// usage
World *world;
initWorld(world);
// this will crash as a side-effect of the failed world initialization (world->things has not been correctly set to NULL)
addThingToWorld(world, &something);

感谢您的帮助,并纠正任何废话我可能会做,我的C背景是pretty此刻差:)

Thank you for your help, and correct any nonsense I might be doing, my C background is pretty poor at the moment :)

好吧,我明白了其实我是一个指针传递给我的函数在第二种情况下,并与当地的malloc重新分配它,以便最终调用者的变量没有改变。但是当我调试还有一些我不明白。在 initWorld 功能,第二种情况下,世界 - >的事情价值分配为NULL后并没有改变。 我也尝试重命名局部变量世界W,我想,也许在调试器显示来电者的变量世界,但没有, W->的东西仍然没有被正确初始化为NULL。

Okay I understood the fact that I was passing a pointer to my function in the second case, and re-assigning it with a local malloc so in the end the caller's variable was not changed. However as I was debugging there is still something I don't understand. In the initWorld function, the second case, the world->things value did not change after the assignation to NULL. I also tried to rename the local variable world to "w", I thought that maybe the debugger was displaying the caller's variable "world", but no, w->things still was not correctly initialized to NULL.

任何提示?

推荐答案

在你的例子,全球是一个指向全球:它指向可以改变的事情,但指针本身不能

In your examples, world is a pointer to World: The things it points to can be altered, but the pointer itself cannot.

您可以传递一个指针的指针的全球来解决这个问题,但我会preFER如果你做一个函数内部分配返回一个指针:

You could pass a pointer to pointer to World to solve this, but I would prefer to return a pointer if you do allocation inside a function:

World *newWorld() 
{
    World *world = malloc(sizeof(*world));

    if (world) world->things = NULL;
    return world;
}

和使用这样的:

World *world = newWorld();

这篇关于结构初始化不使用malloc工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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