简体   繁体   English

如何访问指针结构中的字符串?

[英]How to access a string in a struct of pointers?

I have a structure: 我有一个结构:

struct dispPara
{   
    char *english,   
    char *french,
    void            *value;             
    unsigned char    type;          
    unsigned char    units;                 
};

and

struct dispPara dispParas[5] =
{

 {"abc_english", "xyz_frnch", &blah, blah, blah},

 {"english",  "frnch", &blah, blah, blah},

}

I am accessing english string with: dispParas[i].english. 我正在使用dispParas [i] .english访问英语字符串。 Now, default is english string and if someone changes language to french, pointer should be printing french. 现在,默认值为英文字符串,并且如果有人将语言更改为法语,则指针应为法语。 how can I access french string with a pointer? 如何使用指针访问法语字符串?

Thank you. 谢谢。

It is not clear what you actually want. 目前尚不清楚您真正想要什么。 But if it is for internationalisation, you do it the wrong way, as you cannot index into a struct . 但是,如果是为了国际化,那么您将以错误的方式进行操作,因为您无法索引到struct

Instead, You should use a const char *[] per language (with all strings) and a const char ** which points to the array for the current language. 相反,您应针对每种语言(包含所有字符串)使用const char *[]和指向当前语言数组的const char ** The string would then be current_language[text_index] . 该字符串将是current_language[text_index]

The arrays have to have the same meaning at the same index, of course. 当然,数组必须在相同的索引处具有相同的含义。 To be more clearly you should use an enum for each text instead of a numerical index: 为了更清楚地说明,您应该为每个文本使用一个enum ,而不是一个数字索引:

const char *text_english[] = { "Hello", "World" };
const char *text_german[] = { "Hallo", "Welt" };

typedef enum {
    TEXT_HELLO = 0,
    TEXT_WORLD,
} TextCodes;

const char **current_language = text_english;

...

int main(void)
{
    printf("%s %s!", current_language[TEXT_HELLO], current_language[TEXT_WORLD]);
}

An alternative way would be to use a 2D array: 另一种方法是使用2D数组:

#define NUM_LANGUAGES 2

const char *text_strings[][NUM_LANGUAGES] = {
    { "Hello", "Hallo", },
    { "World", "Welt", },
};

...

size_t lang = 1; // german
printf("%s %s", text_strings[0][lang], text_strings[1][lang]);

The enums above can be used the same way. 上面的enums可以相同的方式使用。 Problem here is that adding a new language will require to change the whole array instead of just adding a new one. 这里的问题是,添加一种新语言将需要更改整个数组,而不仅仅是添加一种新语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM