分配相同类型的多个阵列 [英] Allocating several arrays of the same type

查看:127
本文介绍了分配相同类型的多个阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要分配相同类型和形状的几个阵列。在开始的时候,我确实是这样的:

I need to allocate several arrays of the same type and shape. At the beginning, I did something like:

void alloc_arrays_v1(size_t nmemb)
{
    int *a1, *a2, *a3;

    a1 = malloc(nmemb * sizeof int);
    a2 = malloc(nmemb * sizeof int);
    a3 = malloc(nmemb * sizeof int);

    /* do some stuff with the arrays */

    free(a1);
    free(a2);
    free(a3);
}

要避免调用的malloc 免费几次,我换到上述情况:

To avoid calling malloc and free several times, I changed the above into:

void alloc_arrays_v2(size_t nmemb)
{
    int *a, *a1, *a2, *a3;

    a = malloc(3 * nmemb * sizeof int);
    a1 = a;
    a2 = a1 + nmemb;
    a3 = a2 + nmemb;

    /* do some stuff */

    free(a);
}

这似乎是确定(在这个意义上,该函数的行为在现实世界的情况下以同样的方式),但我不知道这是否仍然有效C code(未定义行为?),如果我能这种方法扩展到复杂的数据类型(结构数组,等等)。

This seems to be ok (in the sense that the functions behave the same way in the real-world case), but I wonder if this is still valid C code (undefined behaviour?), and if I can extend this method to complex data kind (arrays of structs, etc.).

推荐答案

这是完全C.有效,但记得要释放仅 A 指针。你这种方法类似于结构黑客

It is entirely valid in C. But remember to free only the a pointer. Your this method is similar to struct hack

不过,我想在这个code一个逻辑的问题是,如果你去出界了 A1 A2 你将不能够注意到它,你将访问有效的内存地址,即你不会得到赛格故障。结果
然而,在第一种情况下,你可能得到段错误,注意你的错误。

However I think one logical problem in this code is that if you go out of bounds for a1 or a2 you will not be able to notice it as you will be accessing valid memory addresses, i.e. you will not get Seg Fault.
However, in first case you "may" get SegFault and notice your error.

这篇关于分配相同类型的多个阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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