【发布时间】:2017-09-11 05:05:31
【问题描述】:
关于 C 中的 ARM-GCC 当定义一个 const 字符串数组并直接访问它时,字符串被正确放置在 .rodata 部分中。
但是,如果我有一个结构,其中包含指向 .data 部分中的字符串数组的指针并使用 ram。如何将 myStrings 放入只读部分并保存 ram?
const char * myStrings[] = {"String1", "String2"}; //.rodata
const char * myStrings2[] = {"String3", "String4"}; //.data
typdef struct {
const char ** strings;
int a;
} mystruct_t;
const mystruct_t mystruct = {myStrings2,2};
void main()
{
for(uint8_t i=0;i<2;i++)
{
printf("%s",myStrings[i]);
printf("%s",mystruct.strings[i]);
}
}
编辑:提供最少的代码。
【问题讨论】:
-
是字符串本身还是被放置在 .data 中的指针数组?
-
这不是有效的 C 代码。阅读How to Ask 并提供minimal reproducible example!请注意,指针不是数组。
-
...而您在
const mystruct_t = {myStrings,2};中缺少标识符 -
@Dmitri 你是对的!根据大小,它面对存储在数据中的指针(每个字符串 4 字节)。仍然没有必要吗?我可以避免这种情况吗?
-
试试
char const * const myStrings[] = ...。第一个const适用于char(就像在您的原始行中一样),第二个适用于数组中的指针。