从函数中访问Matrix

时间:2021-01-28 15:06:26

I have a large number of strings that I need to store in a character array and I need to be able to loop through all of the strings.

我需要在字符数组中存储大量字符串,我需要能够循环遍历所有字符串。

Furthermore, these strings won't be changing so I want the matrix to be permanent and preferably stored in a header file.

此外,这些字符串不会改变,因此我希望矩阵是永久性的,并且最好存储在头文件中。

Can anyone point me in the right direction?

谁能指出我正确的方向?

I'm working in C and don't know the best way to go about this.

我在C工作,不知道最好的方法。

Thanks!

2 个解决方案

#1


2  

Variable definitions in a header might not be such a good idea, consider alternatives:

标题中的变量定义可能不是一个好主意,请考虑替代方案:

// 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

#2


0  

Try declaring a two level pointer:

尝试声明一个两级指针:

   #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);
   }

This is assuming you are using ANSI C

这假设您使用的是ANSI C.

#1


2  

Variable definitions in a header might not be such a good idea, consider alternatives:

标题中的变量定义可能不是一个好主意,请考虑替代方案:

// 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

#2


0  

Try declaring a two level pointer:

尝试声明一个两级指针:

   #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);
   }

This is assuming you are using ANSI C

这假设您使用的是ANSI C.