指向 void(void*
) 的指针与任何其他指针类型兼容并可以保存任何其他指针类型。对于指向 const void( const void*
) 的指针也是如此吗?
自:
6.3.2.3,p2:对于任何限定符 q,指向非 q 限定类型的指针可以转换为指向 该类型的 q 限定版本;原始指针和转换后指针中存储的值 比较相等。
既然我被允许这样做:
int n = 0 ;
void* p = &n ;
我也应该被允许这样做:
int n = 0 ;
const void* p = &n ;
这引出了我的最后一点,即所有这些也应该适用于复合文字。
void SomeFunc( const void* p ) { printf("%p",p) } ;
SomeFunc( &( int ){ 12345 } ) ;
应该由 C 标准定义(并允许)吗?
最佳答案
我承认我很少发现 C 中需要复合文字,但你的语法绝对是有根据的。如果我正确理解你的问题,它是试图确定上述地址运算符应用于复合文字是否会导致 const
与非常量指针。
除非复合本身是 const 限定的,否则它是非常量。我没有方便的 C99 标准,但我可以为此提供的最佳示例是以下内容中的指导性示例:
C11 standard §6.5.2.5 p11
A read-only compound literal can be specified through constructions like:
(const float []){1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6}
加上复合文字存储限定的描述来自:
C11 standard §6.5.2.5 p5
The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.
所以存储也在那里(即它不驻留在只读存储器中的某个地方)。除非const
限定,复合文字实际上是非常量(如果复合文字数组或结构实际上可能有自己的 const
限定,则其中的数据/元素)。
翻译机制 Type *
到 void*
或const void*
希望是显而易见的,但通过对 sample 进行一些扭转值得注意:
void SomeFunc( void* p ) { printf("%p\n",p); } ;
void SomeFuncConst( const void* p ) { printf("%p\n",p); } ;
int main()
{
SomeFunc( &( int ){ 12345 } ) ; // OK. int* to void*
SomeFuncConst( &( int ){ 12345 } ) ; // OK. int* to const void*
SomeFuncConst &(const int){12345} ); // OK. const int* to const void*
SomeFunc( &( const int ){ 12345 } ) ; // ERROR. const int* not allowed as void*
}
考虑到所有这些,我完全有可能误解了你的问题,如果我能找到删除链接,请澄清一下。
关于c - 对于任何类型,使用 const void* 代替 void*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26239735/