我知道这个问题看起来很奇怪,但我需要在 C 中初始化(或转换)常量字符串数组。
问题是字符串数组是动态初始化的,但我想使用的 API 函数只接受常量字符串数组。
我知道这行得通:
const char *const arr[] = { "test" };
但同样:由于我不知道数组将包含多少项,也不知道运行前的内容,所以我无法以这种方式初始化数组。
所以这当然行不通
const char *const arr[1];
arr[1] = "test"; // won't work
我的问题是:是否可以通过某种方式将动态字符串数组转换为只读数组?或者有没有办法动态初始化数组一次?
编辑 1:我的确切问题
int len = 8;
const char *names1[8] = {"test0","test1","test2","test3","test4","test5","test6","test7" }; // not what I'm looking for
const char *names2[len];
const char *names3[len];
// nearly what I'm looking for
for(int j=0; j<len; j++) {
names2[j] = "test";
}
// exactly what I'm looking for
for(int j=0; j<len; j++) {
sprintf(names3[j],"%s%d","test",j); // discards 'const' qualifier
}
// ...
Cudd_DumpDot(gbm, 1, ddnodearray, names1, NULL, outfile);
Cudd_DumpDot(gbm, 1, ddnodearray, names2, NULL, outfile);
Cudd_DumpDot(gbm, 1, ddnodearray, names3, NULL, outfile); // won't work
好的,这是我目前的进度。
names2
的方法确实有效,但我想使用 sprintf
(如 names3
所示),因为我需要附加 j
在这种情况下。这会伤害 const
限定词。
最佳答案
从技术上讲,没有什么可以阻止您将指针转换为 (char *
),然后使用 memset
或类似方法设置元素。
然而,这会调用未定义的行为,因为编译器可以将它放入标记为只读的内存中。
Excerpt from an answer on another SO question:
The const qualifier is an instruction to the compiler to reject code that attempts to modify that object directly; attempts to modify the object indirectly (as you do in the second code snippet) results in undefined behavior, meaning any result is possible.
无法(不调用 UB)在初始化后更改常量 - 所以不要那样做。
更新 正如@chux 在评论中指出的那样,确实可以动态初始化局部变量。
关于C:动态初始化一个常量字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46834064/