gpt4 book ai didi

常量字符串数组

转载 作者:太空狗 更新时间:2023-10-29 17:04:47 25 4
gpt4 key购买 nike

是否可以有一个(固定的)数组,将其元素存储在可执行文件的只读段中,而不是堆栈中?我想出了这段代码,但不幸的是,它在添加、移动或删除项目时非常不灵活。如何验证字符串确实存储在只读段中?我试过 readelf -a file 但它没有列出字符串。

typedef struct {
int len;
int pos[100];
char data[500];
} FixedStringArray;

const FixedStringArray items = {
4,
{ 9, 14, 19, 24 },
"LongWord1Word2Word3Word4"
} ;

char* GetItem(FixedStringArray *array, int idx, int *len) {
if (idx >= array->len) {
/* Out of range */
*len = -1;
return NULL;
}

if (idx > 0) {
*len = array->pos[idx] - array->pos[idx - 1];
return & array->data[array->pos[idx - 1]];
}

*len = array->pos[idx];
return & array->data[0];
}

void PrintItem(FixedStringArray array, int idx) {
int len;
char *c;
int i = 0;

c = GetItem(&array, idx, &len);

if (len == -1) return;

while (i < len) {
printf("%c", *c);
*c++;
i++;
}
}

我正在考虑为每个数组自动生成结构并为 posdata 使用正确长度的脚本。在内存使用方面是否存在任何问题?或者创建一个结构(如上)以适应所有字符串会更好吗?

最佳答案

我不确定我是否理解您的问题,但您的意思是:

const char * const array[] = { "LongWord1", "Word2", "Word3", "Word4" };

这声明了一个指向常量字符的常量指针数组。

OK,为了避免strlen,怎么样:

struct Str {
size_t len;
char *str;
};
#define STR(s) { sizeof(#s) - 1, #s }
const struct Str[] = { STR(LongWord1), STR(Word2), STR(Word3), STR(Word4) };

关于常量字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1815841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com