【发布时间】:2018-07-14 17:02:20
【问题描述】:
在 C 中,const char *p 有时称为“只读”指针:指向常量对象的指针(在本例中为 char)。
好像
const char **pconst char *const *p
将是指向指针的只读指针的等效声明,具体取决于how many levels of indirection are immutable。
但是,编译器(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)
{
char *ptr = malloc(12*sizeof(char));
strcpy(ptr, "hello world");
printf("before: %s\n", ptr);
readonly(ptr);
printf("after: %s\n", ptr);
free(ptr);
return 0;
}
在函数调用中添加了const 限定符,没有任何抱怨。
指向指针的只读指针
我希望使用指向指针的指针应该可以进行类似的函数调用。
void readonly(const char *const *ptr)
{
// ... do something with ptr ...
// but modifying the object it points to is forbidden
// **ptr = 'j';
}
int main(void)
{
char **ptr;
ptr = (char **) malloc(2*sizeof(char *));
ptr[0] = malloc(14*sizeof(char));
strcpy(ptr[0], "hello world 0");
ptr[1] = malloc(14*sizeof(char));
strcpy(ptr[1], "hello world 1");
printf("before: %s %s\n", ptr[0], ptr[1]);
readonly(ptr);
printf("after: %s %s\n", ptr[0], ptr[1]);
free(ptr[1]);
free(ptr[0]);
free(ptr);
return 0;
}
clang 编译器(6.0.0 版)给出了最易读的警告。
warning: passing 'char **' to parameter of type
'const char *const *' discards qualifiers in nested pointer types
[-Wincompatible-pointer-types-discards-qualifiers]
readonly(ptr);
^~~
note: passing argument to parameter 'ptr' here
void readonly(const char *const *ptr)
但是 gcc (8.1.1) 也会给出警告。
Aside:当我尝试添加限定符时,clang 说传递char ** 丢弃限定符似乎很奇怪?
问题
如何将指向指针(如
char **p)的指针作为“只读”指针传递给函数而不产生警告?如果需要显式转换,为什么是
char **p而不是char *p?
【问题讨论】:
-
指向指针的等效只读指针是
char *const *ptr。 -
"... 有时被称为“只读”指针:..." - 不是由懂语言的人所称。指针是读/写的。你完全被误导了。看看 cdecl 并检查你的教科书。
-
@melpomene 不是。指向指针的 const 指针是
const char ** const pointer。指针星的计数方向相反 - 请参阅我的答案和示例 -
@PeterJ_01 我不是在谈论指向指针的 const 指针。请参阅问题的第一句话:我们正在谈论“指向常量对象的指针”,即指向 char 的 const 指针的指针。 “常量对象”是指向 char 的指针。
-
@melpomene 但您声明指向 const 指针的指针,而不是指向指针的 const 指针