我需要将大量字符串存储在字符数组中,并且我需要能够循环遍历所有字符串。
此外,这些字符串不会改变,因此我希望矩阵是永久性的,并且最好存储在头文件中。
有人能指出我正确的方向吗?
我在C工作,并不知道最好的方法。
谢谢!
答案 0 :(得分:2)
标题中的变量定义可能不是一个好主意,请考虑替代方案:
// source.c contains
const char *const strings[] = {
"string1", "string2", NULL
};
// source.h contains
extern const char *const strings[];
// include source.h anywhere and loop through the strings like this:
for (const char *const *str = strings; *str != NULL; ++str)
// use *str
答案 1 :(得分:0)
尝试声明一个两级指针:
#define NUMBER_OF_ROWS 10
#define MAX_NUMBER_OF_CHARS_IN_STRING 255
char *strings = (char**)calloc(NUMBER_OF_ROWS * sizeof(char));
const char copy_string[] = "default string";
for(int i = 0; i < NUMBER_OF_ROWS; i++)
{
strings[i] = (char*)calloc(MAX_NUMBER_OF_CHARS_IN_STRING);
}
for(int i = 0; i < NUMBER_OF_ROWS; i++)
{
strcpy(strings[i], copy_string);
}
这假设您使用的是ANSI C