如果我声明了一个变量 const char ** stringTable,如果它是一个常量,我应该如何给它赋值? (它必须是 const,因为我应该使用的函数将 const char ** 作为参数。)
编辑:
不,您不能从 char ** 隐式转换为 const char **。编译器提示:
无法将参数 3 从“char **”转换为“const char **”
最佳答案
哇,我很惊讶没有人得到这个!也许我可以得到一个死灵法师徽章。隐式 const 转换仅扫描一层深。所以一个 char*
可以成为const char*
但它不会在 char**
内部挖得足够深键入以查找需要更改的内容以使其成为 const char**
.
#include <iostream>
using namespace std;
void print3( const char **three ) {
for ( int x = 0; x < 3; ++ x ) {
cerr << three[x];
}
}
int main() {
// "three" holds pointers to chars that can't be changed
const char **three = (const char**) malloc( sizeof( char** ) * 3 );
char a[5], b[5], c[5]; // strings on the stack can be changed
strcpy( a, "abc" ); // copy const string into non-const string
strcpy( b, "def" );
strcpy( c, "efg" );
three[0] = a; // ok: we won't change a through three
three[1] = b; // and the (char*) to (const char*) conversion
three[2] = c; // is just one level deep
print3( three ); // print3 gets the type it wants
cerr << endl;
return 0;
}
关于c - 如何将值放入 const char **?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/472362/