char array not assignable

后端 未结 4 934
陌清茗
陌清茗 2020-12-19 17:26

Okay, so I want to save a word in a char array but it gives me a error

Here\'s my code

#include 
#include  
#i         


        
相关标签:
4条回答
  • 2020-12-19 18:05
     class = "Ranger";
    

    should be

    strcpy(class,"Ranger");
    

    Fix the same in all the places. char arrays are not assignable

    0 讨论(0)
  • 2020-12-19 18:07

    see this is not only for character array , this implies for all type of arrays but the question aries why?,when we can assign other variable why not array the thing is:- suppose we have:

    int a[size];
    a = {2,3,4,5,6};
    

    because here the name of an array mean address of the first location of an array

    printf("%p",a); // let suppose the output is 0x7fff5fbff7f0
    

    We are saying by that

    0x7fff5fbff7f0 = something; which is not correct yes we can do a[0] = something , now it saying assign the value of array at 0th location.

    0 讨论(0)
  • 2020-12-19 18:29

    Yes char arrays are not assignable just as all arrays aren't. You should use strcpy for example

    strcpy(class, "Warrior");
    

    and so on.

    Also, you don't need to declare char class[30]; the longest string I see in your code is "undefined" so

    char class[10];
    

    should be ok, 9 characters of "undefined" + 1 null terminating byte '\0'.

    And you should prevent buffer overflow with scanf this way

    scanf("%1s", class);
    

    since you only want to read 1 character, also the comparison should be simpler just

    if (class[0] == 'M')
        strcpy(class, "Mage");
    

    or even thsi would be more readable

    classchosen = 1;
    switch (class[0])
    {
    case 'M':
        strcpy(class, "Mage");
        break;
    case 'R':
        strcpy(class, "Ranger");
        break;
    case 'W':
        strcpy(class, "Warrior");
        break;
    default:
        classchosen = 0;
    }
    

    and finally check that scanf actually succeeded, it returns the number of arguments matched so in your case a check would be like

    if (scanf("%1s", class) == 1) ...
    
    0 讨论(0)
  • 2020-12-19 18:32

    switch class = "Warrior"; to strcpy(class, "warrior");

    switch class = "Mage"; to strcpy(class, "Mage");

    switch class = "Ranger"; to strcpy(class, "Ranger");

    switch class = "undefined"; to strcpy(class, "undefined");

    and it should work !

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