我怎样才能的malloc函数内部结构数组? code,否则工作 [英] How can I malloc a struct array inside a function? Code works otherwise

查看:125
本文介绍了我怎样才能的malloc函数内部结构数组? code,否则工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个用于创建一个可变大小的二维数组FUNCT功能。我用下面的code,这似乎是工作在自己就好了:

I'm trying to create a function that creates a variable sized 2D funct array. I'm using the following code, which seems to work just fine on its own:

typedef struct
{
    //Starter Properties
    int TypeB;
    int TypeF;
    int TypeW;
    //Randomized Properties
    int RandB;
    int RandF;
    int RandW;
    //Derived Properties
    int Speed;
} MapTileData;

MapTileData **Map;

int i, x=5, y=5;

//Allocate Initial Space
Map = (MapTileData**)calloc(x, sizeof(MapTileData));

for(i = 0; i < x; i++)
{
    Map[i] = (MapTileData*)calloc(y, sizeof(MapTileData));
}

所以上面的code创建一个二维数组结构。我试图将code移动到一个功能一直不太成功,要打印的阵列时给予分段错误:

So the above code creates a 2D struct array. My attempts to move the code to a function have been less successful, giving segmentation faults when trying to print the array:

void CreateMap(MapTileData **Map, int xSize, int ySize)
{
    //Variables
    int i;

    //Allocate Initial Space
    Map = (MapTileData**)calloc(xSize, sizeof(MapTileData));

    for(i = 0; i < xSize; i++)
        {
            Map[i] = (MapTileData*)calloc(ySize, sizeof(MapTileData));
        }
}

用于在code:

MapTileData **MapTile;

CreateMap(MapTile,5,5);

任何及所有帮助是极大的AP preciated!

Any and all help is greatly appreciated!

推荐答案

函数的参数是的通过值的传入C和修改在被调用的参数不会影响来电者的局部变量。

Function arguments are passed by value in C and modifying arguments in callee won't affect caller's local variables.

使用指针修改主叫方的局部变量。

Use pointers to modify caller's local variables.

void CreateMap(MapTileData ***Map, int xSize, int ySize)
{
    //Variables
    int i;

    //Allocate Initial Space
    *Map = calloc(xSize, sizeof(MapTileData));

    for(i = 0; i < xSize; i++)
    {
        (*Map)[i] = calloc(ySize, sizeof(MapTileData));
    }
}

在code用法:

MapTileData **MapTile;

CreateMap(&MapTile,5,5);

另一种方法:通过传递返回值的分配的数组

Alternate way: Pass the allocated array via the return value.

MapTileData **CreateMap(int xSize, int ySize)
{
    //Variables
    MapTileData **Map;
    int i;

    //Allocate Initial Space
    Map = calloc(xSize, sizeof(MapTileData));

    for(i = 0; i < xSize; i++)
    {
        Map[i] = calloc(ySize, sizeof(MapTileData));
    }
}

在code用法:

MapTileData **MapTile;

Maptile = CreateMap(5,5);

另外请注意,他们说你不应该投<$结果C $ C>的malloc()及其用C 家庭。

Also note that they say you shouldn't cast the result of malloc() and its family in C.

这篇关于我怎样才能的malloc函数内部结构数组? code,否则工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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