kaetzacoatl
kaetzacoatl

Reputation: 1469

Cast int to void*

I'm trying to create a void* from an int. But gcc always give me a warning, that i cannot cast an int to a void*. Here is my code:

#define M_TABLE_SIZE 64*1024
static const void* M_OFFSET = M_TABLE_SIZE;

I already tried (void*)M_TABLE_SIZE but then I get an error that I cannot use the * operator.

What is the correct method to cast an int to a void*?

Upvotes: 3

Views: 8781

Answers (3)

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37924

For a fairly recent compiler (that supports C99) you should not store or represent address as plain int value. If you really need such trickery, then consider one of dedicated types, which are intptr_t and uintptr_t. Referring to N1570 7.20.1.4/p1 (Integer types capable of holding object pointers):

The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:

intptr_t

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:

uintptr_t

These types are optional.

In your case it might be:

#include <stdint.h>

#define M_TABLE_SIZE ((intptr_t) (64*1024))
static const void* M_OFFSET = (void *) M_TABLE_SIZE;

Upvotes: 1

fhsilva
fhsilva

Reputation: 1257

First you are using a define, which is not a variable. The preprocessor will replace your code by this:

static const void* M_OFFSET = 64*1024;

This is unlikely what you are trying to do.

You may declare a const int variable and cast its reference to the void*.

Upvotes: 0

P.P
P.P

Reputation: 121387

This

static const void* M_OFFSET = (void*)M_TABLE_SIZE;

expands to

static const void* M_OFFSET = (void*)64*1024;

Since gcc compiles that you are performing arithmetic between void* and an int (1024). Put your define inside a bracket:

#define M_TABLE_SIZE (64*1024)

Now, you can do:

static const void* M_OFFSET = (void*) M_TABLE_SIZE;

without a problem. It's always a good practice to put your #define's in brackets to avoid such surprise.

Unless you have a valid address at that value, you are going to invoke undefined behaviour when try to use that pointer. So make sure you understand what you are doing!

Upvotes: 6

Related Questions