本文介绍了如何访问缓存友好的方式灵活数组的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

记录灵活的数组成员

typedef struct record {
    unsigned foo;
    signed bar;
    double number[];
} record;

我有多个记录与等量数字的,所以我可以在阵列排列。我想它们分配到一个连续的内存空间。

I have multiple records with the same amount of numbers so I can arrange them in array. I would like to allocate them into one continuous memory space.

const unsigned numbers = ...;
const unsigned records = ...;
const size_t record_size = sizeof(record) + numbers*sizeof(double);
record *prec = malloc(records*record_size);

所以,现在我知道 record_size ,我可以访问它,但什么是最好的做法,怎么由下式给出记录指数?

So now I know record_size and I can access it but what is best practice how to do it correctly and safely by given record index?

我能做到这一点的时候我都会分离含有号码头,但我想保持记录一起缓存一致性。

I can do it when I would separate header containing foo and bar and numbers, but I would like to keep record together for cache coherency.

推荐答案

因为只有你自己知道的实际布局,C编译器也帮不了你。因此,您必须自己做的地址计算。这将需要一些强制类型转换为字节级做指针算术:

Since only you know the actual layout, the C compiler can't help you. Thus, you must do the address-calculation yourself. It will require some casts to do the pointer-arithmetic at byte level:

record * get_record(record *base, size_t numbers, size_t index)
{
  return (record *) ((unsigned char *) base +
                    index * (sizeof *base + numbers * sizeof *base->number));
}

鉴于上述(和你的code);您可以访问阵列像这样:

Given the above (and your code); you can access the array like so:

record *first = get_record(base, numbers, 0);
first->foo = 4711;
record *second = get_record(base, numbers, 1);
second->foo = 17;

一个明显的缺点是,你将不得不保持号左右值。这可以通过使用显式基地结构整个阵列中,保持每个元素和基指针的大小建模得到改善。当然它可以与元件共同分配本身保持它一起,降低了涉及指针的距离。

One obvious drawback is that you're going to have to keep the numbers value around. This can be improved by modelling the entire array with an explicit "base" structure, that holds the size of each element and the base pointer. Of course it can be co-allocated with the elements themselves to keep it all together and reduce the distances of the involved pointers.

此外,。

Also, please don't cast the return value of malloc() in C.

这篇关于如何访问缓存友好的方式灵活数组的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 16:57