c - 如何将值放入 const char **?

标签 c char constants

如果我声明了一个变量 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/

相关文章:

c++ - 通过const值返回并分配给非const变量进行编译

c++ - C语言在不同架构上的文件操作

c++ - 与通配符匹配的文件名

C++ - 将 FILE* 转换为 CHAR*

c - 无法完全执行 do-while 循环

c++ - 在代码中声明常量或使用数字

c中的函数可以返回long int吗?

c - 用C语言从xml中解析一个字符?

java - 在java中将A字节转换为ASCII字符

c++ - std::launder、std::vector 和 move 仅可构造类型