2012-08-16 49 views
0

我有大量需要存儲在字符數組中的字符串,我需要能夠遍歷所有字符串。從函數中訪問矩陣

此外,這些字符串不會改變,所以我想矩陣是永久性的,最好存儲在頭文件中。

任何人都可以指向正確的方向嗎?

我在C工作,不知道最好的方式去做這件事。

謝謝!在頭

回答

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 
+0

非常感謝! – JupiterOrange 2012-08-16 23:41:41

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