Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: incompatible types in assignment of 'char*' to 'char [20]'

I'm new to this C++ environment and I am having difficulty with my constructor. Here is my code:

class Student {
    char name[20];
    long number;
public:
    Student (char nm[20], long val) : 
         name(nm), number(val) {}

When I compile it, it gives me an error saying incompatible types in assignment of char* to char[20].

How can i fix this??

like image 785
Ananymus Avatar asked Oct 26 '25 20:10

Ananymus


1 Answers

Your constructor argument nm is, actually, not an array! Yes, I know it looks like one, because you wrote char nm[20]. But, actually, it's char* nm. That translation is performed automatically when you write an array type in a function parameter list. Yes, it's stupid. Blame C.

So, the error message is telling you that you cannot assign a pointer to an array. Fair enough. Doesn't really matter anyway, since the language also doesn't let you assign arrays to arrays. Lol.

This is why, since 1998, we've had std::string to fix all these terrible problems:

class Student {
    std::string name;
    long number;
public:
    Student (std::string nm, long val) : 
         name(nm), number(val) {}
};

If you must use an array, you can do this:

class Student {
    std::array<char, 20> name;
    long number;
public:
    Student (std::array<char, 20> nm, long val) : 
         name(nm), number(val) {}
};

because std::array, introduced in 2011, is a handy wrapper around raw arrays that can be assigned (and don't have that weird decay to pointers!).

"Ah, but my teacher told me to use raw arrays," I hear you say. A shame, but we can fix that too. Either accept the array by reference, or take in a pointer to it (as you're doing now! but this drops the dimension 20 from the type and makes things unsafe -.-) and do a manual copy of each element from the source to the destination. Certainly not ideal, but it may be what your teacher is expecting if this is homework:

class Student {
    char name[20];
    long number;
public:
    Student (char (&nm)[20], long val) : 
         number(val)
    {
       assert(sizeof(nm) == sizeof(name));
       std::copy(std::begin(nm), std::end(nm), std::begin(name));
    }
};

class Student {
    char name[20];
    long number;
public:
    Student (char* nm, long val) : 
         number(val)
    {
       // just have to hope that the input is a pointer to **20** elements!
       std::copy(nm, nm+20, name);
    }
};
like image 110
Lightness Races in Orbit Avatar answered Oct 28 '25 09:10

Lightness Races in Orbit