的malloc在C结构和指针 [英] malloc for struct and pointer in C

查看:85
本文介绍了的malloc在C结构和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想定义的载体的结构重新presenting长度和值:

 结构向量{
    双* X;
    INT N;
};

现在,假设我要定义一个向量y,并为其分配内存。

 结构向量* Y =(结构向量*)malloc的(的sizeof(结构向量));

我的搜索在互联网上节目,我应该单独分配内存对于x

  Y-GT; X =(双*)malloc的(10 * sizeof的(双));

不过,似乎我为y轴分配内存>两次x,之一,而y的分配内存和其他分配时为Y-> X存储器,似乎浪费内存。
这是,如果让我知道什么是真正的编译器做,什么将是正确的做法非常AP preciated
初始化两个Y,和Y系列> X

先谢谢了。


解决方案

没有,你的的为 Y-GT分配内存; X 两次。

相反,你的结构分配内存(其中包括一个指针)的以及的东西的指针指向。

考虑一下这种方式:

  1 2
        + ----- + + + ------
Ÿ------> |点¯x------> | * X |
        | N | + ------ +
        + ----- +

所以,你真正需要的两笔拨款( 1 2 )来存储所有内容。

此外,你的类型应该是结构向量* Y 因为它是一个指针,你永远不应该从的malloc将返回值用C,因为它可以隐藏你不想隐藏的一些问题 - C是完全有能力的无效* 返回值隐含转换为任何其他指针<。 / p>

和,当然,你可能想封装这些载体的创建,使他们的管理更加容易,如:

 结构向量{
    双*的数据; // x和n的可读性code :-)没有立足之地
    为size_t的大小;
};结构向量* newVector(为size_t SZ){
    //尝试分配向量结构。    结构向量* retVal的malloc的=(的sizeof(结构向量));
    如果(RETVAL == NULL)
        返回NULL;    //尝试,如果无法分配矢量数据,免费结构。    retVal-&GT;数据=的malloc(SZ *的sizeof(双));
    如果(retVal-&GT;数据== NULL){
        免费(retVal的);
        返回NULL;
    }    //设置规模和回报。    retVal-&GT;大小= SZ;
    返回retVal的;
}无效delVector(结构向量*向量){
    //可以安全地假设向量为NULL,或完全建成。    如果(矢量!= NULL){
        免费(病媒&GT;数据);
        免费(矢量);
    }
}

通过封装这样的创作,可以确保向量要么完全建成或没有内置在所有 - 有没有他们的机会是一半建。它也可以让你彻底改变未来的底层数据结构,而不会影响客户端(例如,如果你想使它们稀疏数组权衡速度空间)。

Suppose I want to define a structure representing length of the vector and its values as:

struct Vector{
    double* x;
    int n;
};

Now, suppose I want to define a vector y and allocate memory for it.

struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector));

My search over the internet show that I should allocate the memory for x separately.

y->x = (double*)malloc(10*sizeof(double));

But, it seems that I am allocating the memory for y->x twice, one while allocating memory for y and the other while allocating memory for y->x, and it seems a waste of memory. It is very much appreciated if let me know what compiler really do and what would be the right way to initialize both y, and y->x.

Thanks in advance.

解决方案

No, you're not allocating memory for y->x twice.

Instead, you're allocating memory for the structure (which includes a pointer) plus something for that pointer to point to.

Think of it this way:

         1          2
        +-----+    +------+
y------>|  x------>|  *x  |
        |  n  |    +------+
        +-----+

So you actually need the two allocations (1 and 2) to store everything.

Additionally, your type should be struct Vector *y since it's a pointer, and you should never cast the return value from malloc in C since it can hide certain problems you don't want hidden - C is perfectly capable of implicitly converting the void* return value to any other pointer.

And, of course, you probably want to encapsulate the creation of these vectors to make management of them easier, such as with:

struct Vector {
    double *data;    // no place for x and n in readable code :-)
    size_t size;
};

struct Vector *newVector (size_t sz) {
    // Try to allocate vector structure.

    struct Vector *retVal = malloc (sizeof (struct Vector));
    if (retval == NULL)
        return NULL;

    // Try to allocate vector data, free structure if fail.

    retVal->data = malloc (sz * sizeof (double));
    if (retVal->data == NULL) {
        free (retVal);
        return NULL;
    }

    // Set size and return.

    retVal->size = sz;
    return retVal;
}

void delVector (struct Vector *vector) {
    // Can safely assume vector is NULL or fully built.

    if (vector != NULL) {
        free (vector->data);
        free (vector);
    }
}

By encapsulating the creation like that, you ensure that vectors are either fully built or not built at all - there's no chance of them being half-built. It also allows you to totally change the underlying data structures in future without affecting clients (for example, if you wanted to make them sparse arrays to trade off space for speed).

这篇关于的malloc在C结构和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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