简体   繁体   English

typedef在C中存储指针

[英]typedef to store pointers in C

The Size of pointer depends on the arch of the machine. 指针的大小取决于机器的拱形。

So sizeof(int*)=sizeof(int) or sizeof(int*)=sizeof(long int) 所以sizeof(int *)= sizeof(int)或sizeof(int *)= sizeof(long int)

I want to have a custom data type which is either int or long int depending on the size of pointer. 我希望有一个自定义数据类型,它是int或long int,具体取决于指针的大小。

I tried to use macro #if, but the condition for macros does not allow sizeof operator. 我试图使用宏#if,但宏的条件不允许sizeof运算符。

Also when using if-else, typedef is limited to the scope of if. 另外,当使用if-else时,typedef仅限于if的范围。

if((sizeof(int)==sizeof(int *)){
  typedef int ptrtype;
}
else{
  typedef long int ptrtype;
}
//ptrtype not avialble here

Is there any way to define ptrtype globally? 有没有办法在全球范围内定义ptrtype?

在C99中,您可以使用intptr_t

The traditional way to do this used to be to use GNU autoconf (or similar) to set up some defines such as SIZEOF_VOIDPTR , but if you have a sufficiently recent compiler the type intptr_t may well be what you want. 传统的方法是使用GNU autoconf(或类似的)来设置一些定义,如SIZEOF_VOIDPTR ,但如果你有一个足够新的编译器, intptr_t类型可能就是你想要的。 (You might need to set some compiler flags to enable C99 mode; it's in <stdint.h> .) (您可能需要设置一些编译器标志以启用C99模式;它位于<stdint.h> 。)

当然,使用<stdint.h>定义的intptr_tuintptr_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM