为什么我不能转换“的char **'到'为const char * const的*”用C? [英] Why can't I convert 'char**' to a 'const char* const*' in C?

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

问题描述

以下code段(正确)给出了一个在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的*,这规避常量,正确性(的 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)什么是去接受这个字符**作为参数一边说(和具有强制执行的编译器),我不会修改它指向字符的正确方法是什么?
例如,如果我想编写一个函数:

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?

编辑:
谢谢那些谁回应,特别是针对谁的问题和/或跟进我的反应。

Thank you to those who have responded, particularly those who addressed the question and/or followed up on my responses.

我已经接受了答案我想做的事情不能没有投来完成,不管它是否应该是可能的。

I've accepted the answer that what I want to do cannot be done without a cast, regardless of whether or not it should be possible.

推荐答案

我在几年前就有这种问题,这惹恼我没有尽头。

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

在C中的规则更简单地说(即他们没有列出像字符转换** 为const char * const的异常* )。 Consequenlty,它只是不允许的。随着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.

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

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