How to Initialize char array from a string

后端 未结 11 2013
时光说笑
时光说笑 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 09:47

    I'm not sure what your problem is, but the following seems to work OK:

    #include 
    
    int main()
    {
        const char s0[] = "ABCD";
        const char s1[] = { s0[3], s0[2], s0[1], s0[0], 0 };
    
        puts(s0);
        puts(s1);
        return 0;
    }
    
    
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
    Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
    cl /Od /D "WIN32" /D "_CONSOLE" /Gm /EHsc /RTC1 /MLd /W3 /c /ZI /TC
       .\Tmp.c
    Tmp.c
    Linking...
    
    Build Time 0:02
    
    
    C:\Tmp>tmp.exe
    ABCD
    DCBA
    
    C:\Tmp>
    

    Edit 9 June 2009

    If you need global access, you might need something ugly like this:

    #include 
    
    const char *GetString(int bMunged)
    {
        static char s0[5] = "ABCD";
        static char s1[5];
    
        if (bMunged) {
            if (!s1[0])  {
                s1[0] = s0[3]; 
                s1[1] = s0[2];
                s1[2] = s0[1];
                s1[3] = s0[0];
                s1[4] = 0;
            }
            return s1;
        } else {
            return s0;
        }
    }
    
    #define S0 GetString(0)
    #define S1 GetString(1)
    
    int main()
    {
        puts(S0);
        puts(S1);
        return 0;
    }
    

提交回复
热议问题