thetna
thetna

Reputation: 7143

Proper way of using simple integer and memsizes

I would like to know what is the proper way of using simple integer and memsize?To be precise, I have a C code initially written for 32 bit architecture. Now it has to run into both the architecture, So there is obvious reason to get the following warning,while running in 64 bit architecture

 warning: cast to pointer from integer of different size

I am trying to remove those warnings using the memsize, intptr_t and uintptr_t. But I have a doubt if it works properly if we use mixed simple integer and memsizes. I would like to know the proper way of using it. Following is the sample of code.

  compllits = list_Cons((POINTER) predindex, compllits);

Here compllits is a linked list and is defined as pointer . list_Cons returns pointer. list_Cons is defined as:

list_Cons(POINTER x, LIST y);

And, int preindex. I am casting the integer into Pointer. As I run it in 64-bit machine , I will get the warning

 : warning: cast to pointer from integer of different size

Now to resolve this warning, I am liitle bit confused in the two methods I am using ,

     Method 1: changing the int preindex into intptr_t preindex.

     Method 2. Keeping  int preindex unchanged but doing following

       compllits = list_Cons((POINTER)(intptr_t)predindex, compllits);

Both the ways are working. But I am not sure which method is legal and best? Looking for some suggestions.

Thanks

Upvotes: 0

Views: 208

Answers (2)

Lindydancer
Lindydancer

Reputation: 26134

The big question is if you really have to mix pointers and integers. (The few cases where this is the case is when handling lisp-like generic data structures.) If not, you should use the correct type, and that type only.

However, if this is the case, do you really need to handle them using the same function? For example, you could have list_Cons_pointer and list_Cons_int that accept a real pointer and an integer type matching preindexed, respectively.

Whether or not you should change the type of preindexed really depends on what it represents in the program.

Apart from this, an intptr_t is guaranteed to be large enough to hold a pointer, but it might be larger. This means that there is really no way to get rid of all warnings in all possible environments (think 48 bit pointers...)

Upvotes: 2

Michael Closson
Michael Closson

Reputation: 932

Is preindex really a pointer? If so then your problem is using int as a pointer type. Use int *.

Also, I'd recommend using int * rather than intptr_t. intptr_t is an integer that is wide enough to hold a pointer, but semantically it is still an integer.

On a 32bit machine, int is 32 bits wide and int * is also 32 bits wide. On a 64 bit machine int is still 32 bits wide, but int * is 64 bits wide.

Upvotes: 0

Related Questions