本文介绍了验证字符串(如文字,数组,指针)的类型传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数,它接受一个字符数组,其大小:
I have a function, which takes a character array and its size:
void store_string (const char *p, size_t size); // 'p' & 'size' stored in map
的功能由一个宏为包裹
The function is wrapped by a macro as:
#define STORE_STRING(X) store_string(X, sizeof(X))
我的问题是,我想以某种方式禁止或通知,只有字符串应传递给此功能的用户。因为,如果任何指针或本地阵列存储在地图中那么他们可能会走出去的范围,创造浩劫!
My problem is that I want to somehow prohibit or inform user that only string literal should be passed to this function. Because, if any pointer or local array are stored inside the map then they might go out of scope and create a havoc!
有没有编译时的方式(preferred),或至少运行时的方式去做?
Is there any compile-time way (preferred) or at least run-time way to do it?
推荐答案
您能知道它的编译时间,通过简单地改变你的宏:
You can know it compile time, by simply changing your macro to:
#define STORE_STRING(X) store_string("" X, sizeof(X))
用法:
char a[] = "abcd", *p;
STORE_STRING(a); // error
STORE_STRING(p); // error
STORE_STRING("abcd"); // ok
这篇关于验证字符串(如文字,数组,指针)的类型传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!