简体   繁体   English

C语言:隐式指针解引用

[英]C language: implicit pointer dereferencing

In C, is it possible to define an alias / shortcut for a dereferenced pointer? 在C语言中,是否可以为已取消引用的指针定义别名/快捷方式?

Ie assuming a definition like: 即假设像这样的定义:

void * ptr_to_my_variable = 0x2ff00000;

Is it possible to define a my_variable symbol that corresponds to *ptr_to_my_variable , such that: 是否可以定义与*ptr_to_my_variable对应的my_variable符号,例如:

*ptr_to_my_variable = 321;
my_variable = 123;
if (my_variable == *ptr_to_my_variable) printf "aliasing/shortcut works";

The only solution I can think of is: 我能想到的唯一解决方案是:

#define my_variable *my_variable
int my_variable = (int *) 0x2ff00000;

my_variable = 123;

But this is clearly asking for trouble... 但这显然是在麻烦...

No, there is no trick that would let you dereference a pointer implicitly. 不,没有任何技巧可以让您隐式取消引用指针。

However, preprocessor trick that youmentioned in the edit lets you hide the explicit dereference, making it look implicit: 但是,您在编辑中提到的预处理器技巧可让您隐藏显式的取消引用,使其看起来是隐式的:

#define my_alias (*my_var_ptr)

Note, however, that you should place parentheses around the expression, which wiuld save you from trouble when you write 但是请注意,您应该在表达式周围放置括号,这样可以避免编写时遇到麻烦

my_alias++;

Nope, the #define is the only way to do this in C. 不,# #define是在C语言中执行此操作的唯一方法。

C++ has things called "references" which are implicitly dereferenced, but can (must?) alias other objects. C ++具有被称为“引用”的事物,这些事物被隐式取消引用,但是可以(必须?)为其他对象提供别名。 You'd have to ask somebody else about the details. 您必须向其他人询问有关细节。 But C does not support any such thing. 但是C不支持任何这样的事情。

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

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