C - 将int指针存储在整数中

Tom*_*mmy 2 c 64-bit pointers integer

我有任何int类型的数组,需要在这个数组中存储一个指向数组另一部分的指针.

问题是,在64位系统上,指针的大小是8个字节,int的大小是4个字节,导致编译器警告(例如警告从不同大小的整数转换为指针)

我(想想我理解为什么编译器在呻吟,显然尝试将8个字节装入4个字节并不是一个聪明的主意.问题是数组是按原样提供给我的,我必须只使用数组进行存储.

Sim*_*one 6

如果你指的是同一个数组,为什么不只存储索引呢?

#include <limits>
#include <boost/static_assert.hpp>

int array[ARRAY_DIMENSION];

/**
 * the following line will cause an error at compile-time if size_t
 * is not enough to index the array.
 */

BOOST_STATIC_ASSERT(std::numeric_limits<size_t>::max() >= ARRAY_DIMENSION);

int access_array(size_t index)
{
    size_t intended_index = array[index];
    return array[intended_index];
}
Run Code Online (Sandbox Code Playgroud)