我正在构建一个长度最多为 20 的 10 个字符串的数组
char buffer[10][20] = {0};
//populate the buffer with 10 strings
//after this point, no more changes to the buffer allowed
//make a new pointer to indicate that I want the buffer finalized
const char **finalized = buffer;
但是之前的失败并出现警告
warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
用单个字符串做类似的事情是可行的
char buffer[20] = {0};
//populate the buffer
const char *finalized = buffer;
在第一种情况下,正确的转换方式是什么?
最佳答案
将常规二维数组“转换”为指针到指针类型是不可能的。这些类型完全不兼容并且具有完全不同的语义。您可以强制转换,但无论如何结果都是无用的。
形式上,这种情况下正确的指针类型是 char (*)[20]
char (*finalized)[20] = buffer;
除了 C 语言的 const-correctness 规则不允许您在那里添加 const
。你可以强制它
const char (*finalized)[20] = (const char (*)[20]) buffer;
你也可以这样做
char (*finalized)[10][20] = &buffer;
这对您是否有用 - 我不知道,因为您没有提供任何有关其用途的详细信息。
关于c - 如何将 char[n][length+1] 转换为 C 中的常量字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42035965/