我正在开发一个在数组中包含字符串的应用程序:
static char * strings[] = {
"ABC DEF",
"EF",
"GHI"
};
Run Code Online (Sandbox Code Playgroud)
注意,该类型没有const修饰符!
在我的应用程序中,我循环数组并还原字符串.预期的结果是:
{
"FED CBA",
"FE",
"IHG"
}
Run Code Online (Sandbox Code Playgroud)
但是我得到的结果是:
{
"FED CAB",
"AB",
"IHG"
}
Run Code Online (Sandbox Code Playgroud)
原因是因为在原始数组中,字符串被编译为重叠:strings [1]与字符串[0]的末尾重叠!
// When I printed out the pointers it turned out that in the RAM
// it stored my strings "overlapping":
// 00 01 02 03 04 05 06 07 08 09 0a 0b
// "A B C __ D E F \0 G H I \0"
static char * strings[] = {
0x00, 0x05, 0x08
};
Run Code Online (Sandbox Code Playgroud)
有没有办法(除了没有不起作用的const修饰符)告诉编译器不要重叠我的字符串?这是编译器或我的代码中的错误吗?我可以做什么工作?
您正在获取未定义的行为,因为您正在修改实现为char *指向字符串文字的字符串,这是无效的.
您必须将它们放在显式数组中,以确保它们是可修改的:
static char str1[] = "ABC DEF", str2[] = "EF", str3[] = "GHI";
static char * strings[] = { str1, str2, str3 };
Run Code Online (Sandbox Code Playgroud)
请注意,所有str字符串都有类型char [],而不是char *正确的数组.const当然,非阵列总是可以修改的.
如果您愿意提交最大字符串长度,则可以执行2D数组类型的声明以使其更紧凑:
static char strings[][10] = { "ABC DEF", "EF", "GHI" };
Run Code Online (Sandbox Code Playgroud)
顺便说一下,这个问题几乎是一个XY问题.