如何使用sizeof检测指针?

时间:2022-09-06 14:17:50

I want to replace the sprintf() to snprintf() of my project. So I write a shell to replace sprintf() to MY_SPRINTF and then,

我想将sprintf()替换为我项目的snprintf()。所以我写了一个shell来将sprintf()替换为MY_SPRINTF,然后,

#define MY_SPRINTF(buf,args...)  snprintf(buf,sizeof(buf), ## args).

However, the parameter "buf" is a pointer somewhere in my project that make my replacement not work correctly.

但是,参数“buf”是我项目中某处的指针,使我的替换无法正常工作。

I want to figure out whether the parameter "buf" is a pointer when compiling. Is it possible ?

我想弄清楚参数“buf”在编译时是否是指针。可能吗 ?

2 个解决方案

#1


0  

I want to figure out whether the parameter "buf" is a pointer when compiling. Is it possible ?

我想弄清楚参数“buf”在编译时是否是指针。可能吗 ?

Arrays and pointers can be distinguished during compile time, see the answers of this question. After you replaced sprintf by a MY_SPRINTF rejecting pointers the compiler halts when sprintf is used with a pointer so you need not to check every replacement manually.

在编译期间可以区分数组和指针,请参阅此问题的答案。在通过MY_SPRINTF拒绝指针替换sprintf之后,当sprintf与指针一起使用时编译器会停止,因此您无需手动检查每个替换。

#define ARRAY_SNPRINTF(buf,...)  \
    snprintf(buf,_Generic(&buf, char (*)[]:sizeof(buf),default:(void)0), __VA_ARGS__)

#2


2  

You can't do it, you should not do it, just search for every occurrance of it and fix it accordingly.

你不能这样做,你不应该这样做,只是搜索它的每一个出现并相应地修复它。

If buf is an array it will work with sizeof() otherwise there is no way to know the size of the allocated pointer.

如果buf是一个数组,它将使用sizeof(),否则无法知道分配指针的大小。

#1


0  

I want to figure out whether the parameter "buf" is a pointer when compiling. Is it possible ?

我想弄清楚参数“buf”在编译时是否是指针。可能吗 ?

Arrays and pointers can be distinguished during compile time, see the answers of this question. After you replaced sprintf by a MY_SPRINTF rejecting pointers the compiler halts when sprintf is used with a pointer so you need not to check every replacement manually.

在编译期间可以区分数组和指针,请参阅此问题的答案。在通过MY_SPRINTF拒绝指针替换sprintf之后,当sprintf与指针一起使用时编译器会停止,因此您无需手动检查每个替换。

#define ARRAY_SNPRINTF(buf,...)  \
    snprintf(buf,_Generic(&buf, char (*)[]:sizeof(buf),default:(void)0), __VA_ARGS__)

#2


2  

You can't do it, you should not do it, just search for every occurrance of it and fix it accordingly.

你不能这样做,你不应该这样做,只是搜索它的每一个出现并相应地修复它。

If buf is an array it will work with sizeof() otherwise there is no way to know the size of the allocated pointer.

如果buf是一个数组,它将使用sizeof(),否则无法知道分配指针的大小。