在C语言中,有没有好的方法先定义长度,Pascal风格的字符串作为常量,这样就可以放在ROM中了? (我正在使用一个带有非 GCC ANSI C 编译器的小型嵌入式系统)。
C 字符串以 0
终止,例如。 {'f'
,'o'
,'o'
,0
}。
Pascal 字符串的长度在第一个字节,例如。 {3
,'f'
,'o'
,'o'
}.
我可以声明一个 C 字符串放在 ROM 中:
const char *s = "foo";
对于 Pascal 字符串,我可以手动指定长度:
const char s[] = {3, 'f', 'o', 'o'};
但是,这很尴尬。有没有更好的办法?也许在预处理器中?
最佳答案
我认为以下是一个很好的解决方案,但不要忘记启用打包结构:
#include <stdio.h>
#define DEFINE_PSTRING(var,str) const struct {unsigned char len; char content[sizeof(str)];} (var) = {sizeof(str)-1, (str)}
DEFINE_PSTRING(x, "foo");
/* Expands to following:
const struct {unsigned char len; char content[sizeof("foo")];} x = {sizeof("foo")-1, "foo"};
*/
int main(void)
{
printf("%d %s\n", x.len, x.content);
return 0;
}
一个问题是,它在您的字符串之后添加了一个额外的 NUL 字节,但它可能是可取的,因为这样您也可以将它用作普通的 c 字符串。您还需要将其转换为您的外部库期望的任何类型。
关于c - 在 C 中声明 Pascal 风格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7648947/