Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Storing an int pointer in an integer

I have any array of type int and need to store, within this array, a pointer to another part of the array.

The problem is that, on 64bit systems, the size of the pointer is 8 bytes, and the size of the int is 4 bytes causing complier warnings (e.g. warning cast to pointer from integer of different size)

I (think0 i understand why the complier is moaning, obviously trying to fit 8 bytes into 4 bytes isn't a clever idea. The problem is the array is supplied to me as is and I must use only the array for storage.

like image 920
Tommy Avatar asked Apr 29 '26 11:04

Tommy


1 Answers

If you are referring to the same array, why don't you store just the index?

#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];
}
like image 94
Simone Avatar answered May 01 '26 01:05

Simone