为什么我不能在 C 中将 'char**' 转换为 'const char* const*'? [英] Why can't I convert 'char**' to a 'const char* const*' in C?

查看:28
本文介绍了为什么我不能在 C 中将 'char**' 转换为 'const char* const*'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码片段(正确)在 C 中给出警告,在 C++ 中给出错误(分别使用 gcc 和 g++,在 3.4.5 和 4.2.1 版本中测试;MSVC 似乎并不关心):

The following code snippet (correctly) gives a warning in C and an error in C++ (using gcc & g++ respectively, tested with versions 3.4.5 and 4.2.1; MSVC does not seem to care):

char **a;
const char** b = a;

我可以理解并接受这一点.
这个问题的 C++ 解决方案是将 b 更改为 const char * const *,这不允许重新分配指针并防止您规避 const-correctness (C++ 常见问题解答).

I can understand and accept this.
The C++ solution to this problem is to change b to be a const char * const *, which disallows reassignment of the pointers and prevents you from circumventing const-correctness (C++ FAQ).

char **a;
const char* const* b = a;

但是,在纯 C 中,更正后的版本(使用 const char * const *)仍然会发出警告,我不明白为什么.有没有办法在不使用演员表的情况下解决这个问题?

However, in pure C, the corrected version (using const char * const *) still gives a warning, and I don't understand why. Is there a way to get around this without using a cast?

澄清一下:
1) 为什么这会在 C 中产生警告?它应该是完全 const 安全的,而且 C++ 编译器似乎也能识别它.
2)在说(并让编译器强制执行)我不会修改它指向的字符的同时,接受这个 char** 作为参数的正确方法是什么?比如我想写一个函数:

To clarify:
1) Why does this generate a warning in C? It should be entirely const-safe, and the C++ compiler seems to recognize it as such.
2) What is the correct way to go about accepting this char** as a parameter while saying (and having the compiler enforce) that I will not be modifying the characters it points to? For example, if I wanted to write a function:

void f(const char* const* in) {
  // Only reads the data from in, does not write to it
}

我想在 char** 上调用它,参数的正确类型是什么?

And I wanted to invoke it on a char**, what would be the correct type for the parameter?

推荐答案

几年前我也遇到过同样的问题,这让我很恼火.

I had this same problem a few years ago and it irked me to no end.

C 中的规则更简单地说明(即它们没有列出将 char** 转换为 const char*const* 之类的例外情况).结果,就是不允许.在 C++ 标准中,它们包含了更多允许此类情况的规则.

The rules in C are more simply stated (i.e. they don't list exceptions like converting char** to const char*const*). Consequenlty, it's just not allowed. With the C++ standard, they included more rules to allow cases like this.

最后,这只是C标准中的一个问题.我希望下一个标准(或技术报告)能解决这个问题.

In the end, it's just a problem in the C standard. I hope the next standard (or technical report) will address this.

这篇关于为什么我不能在 C 中将 'char**' 转换为 'const char* const*'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆