返回指向宏中某个值的指针?
是否可以编写一个具有类型和值作为其输入参数的宏 (MACRO(type,value)
),并返回一个指向保存所提交值的位置的有效指针
。
该宏的执行方式应类似于以下函数,但采用更通用的方式:
int *val_to_ptr(int val){
int *r = NULL;
r = nm_malloc(sizeof(*r));
*r = val;
return r;
}
其中 nm_malloc()
是故障安全 malloc。 宏的用法应该与此用法兼容:
printf("%d",*MACRO(int,5));
是否可以实现?
Is it possible to write a macro that has a type and a value as its input parameters (MACRO(type,value)
), and returns a valid pointer to a location that holds the submitted value
.
This macro should perform like the following function, but in a more generic manner:
int *val_to_ptr(int val){
int *r = NULL;
r = nm_malloc(sizeof(*r));
*r = val;
return r;
}
Where nm_malloc()
is a failsafe malloc.
The Macro usage should be compatible with this usage:
printf("%d",*MACRO(int,5));
Is it possible to achieve that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 gcc,则可以使用语句表达式:
If you're using gcc, you can use statement expressions:
也许(未经测试):
用法
Perhaps (untested):
Usage
这是一个以 C++ 模板为模型的实现,
您必须显式定义要使用它的类型,并且必须输入诸如
unsigned int
或double complex
之类的内容> 否则令牌粘贴将不起作用。交替使用
和调用
,而不必担心参数评估
Here's an implementation which is modelled on c++ templates
You'd have to explicitly define what types you're using it for, and would have to typedef things like
unsigned int
ordouble complex
or the token paste won't work.Alternately use
and call
without having to worry about argument evaluation
任何使用
malloc()
的解决方案都会导致您给出的示例中的内存泄漏。然而,这个使用 C99 复合文字的简单解决方案不会:Any of the solutions using
malloc()
will cause a memory leak in the example you gave. However, this simple solution, using C99 compound literals, does not: