在C中,const char *p有时称为"只读"指针:指向常量对象的指针(在本例中为a char).
看起来似乎也是如此
const char **pconst char *const *p将是指向指针的只读指针的等效声明,具体取决于间接的多少级别是不可变的.
但是,编译器(gcc,clang)会生成警告.
我的问题:如何在char **p没有生成警告的情况下将指针(如)作为"只读"指针传递给函数?如果需要明确的演员表,为什么char **p不是char *p?
这是我想要实现的具体例子.
此代码视为char *ptr只读指针.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void readonly(const char *ptr)
{
// ... do something with ptr ...
// but modifying the object it points to is forbidden
// *ptr = 'j'; // error: read-only variable is not assignable
}
int main(void)
{ …Run Code Online (Sandbox Code Playgroud)