How to Initialize char array from a string

后端 未结 11 1995
时光说笑
时光说笑 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:05

    This compiles fine on gcc version 4.3.3 (Ubuntu 4.3.3-5ubuntu4).

    const char s[] = "cheese";
    
    int main()
    {
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-14 10:07

    Perhaps your character array needs to be constant. Since you're initializing your array with characters from a constant string, your array needs to be constant. Try this:

    #define S "ABCD"
    const char a[] = { S[0], S[1], S[2], S[3] };
    
    0 讨论(0)
  • 2020-12-14 10:09
    const char S[] = "ABCD";
    

    This should work. i use this notation only and it works perfectly fine for me. I don't know how you are using.

    0 讨论(0)
  • 2020-12-14 10:10

    Another option is to use sprintf.

    For example,

    char buffer[50];
    sprintf( buffer, "My String" );
    

    Good luck.

    0 讨论(0)
  • 2020-12-14 10:11

    Simply

    const char S[] = "ABCD";
    

    should work.

    What's your compiler?

    0 讨论(0)
提交回复
热议问题