How to Initialize char array from a string

后端 未结 11 2012
时光说笑
时光说笑 2020-12-14 09:19

I want to do the following

char a[] = { \'A\', \'B\', \'C\', \'D\'};

But I do not want to write these characters separately. I want somethi

11条回答
  •  悲哀的现实
    2020-12-14 10:03

    The compilation problem only occurs for me (gcc 4.3, ubuntu 8.10) if the three variables are global. The problem is that C doesn't work like a script languages, so you cannot take for granted that the initialization of u and t occur after the one of s. That's why you get a compilation error. Now, you cannot initialize t and y they way you did it before, that's why you will need a char*. The code that do the work is the following:

    #include 
    #include 
    
    #define STR "ABCD"
    
    const char s[] = STR;
    char* t;
    char* u;
    
    void init(){
        t = malloc(sizeof(STR)-1);
        t[0] = s[0];
        t[1] = s[1];
        t[2] = s[2];
        t[3] = s[3];
    
    
        u = malloc(sizeof(STR)-1);
        u[0] = s[3];
        u[1] = s[2];
        u[2] = s[1];
        u[3] = s[0];
    }
    
    int main(void) {
        init();
        puts(t);
        puts(u);
    
        return EXIT_SUCCESS;
    }
    

提交回复
热议问题