Muhammad Arslan Jamshaid
Muhammad Arslan Jamshaid

Reputation: 1197

How to assign char instance of a class

class demoClass {
private:
    char item_name[50];

public:
    void set_item_name(char *item_name){ this->item_name=item_name; };
};

I am receiving error : invalid assignment of char to char[50]

Upvotes: 2

Views: 428

Answers (3)

Seth Carnegie
Seth Carnegie

Reputation: 75130

You are trying to assign a pointer to an array. You really want to copy the string that is pointed to by the char* to your array:

void set_item_name(char *item_name){
    strncpy(this->item_name, item_name, 50);
    this->item_name[49] = 0; // because if the string is longer than 50, it won't be NULL terminated
};

If you don't want to keep a copy of it and just want to retain a pointer to it (and you trust that that memory won't be deallocated, you can just store the pointer by changing item_name to a char* and keeping everything else like it was in your original code.

Upvotes: 2

krammer
krammer

Reputation: 2658

Arrays and pointer are not same:

Try:

void set_item_name(char item_name[]){strcpy(this->item_name,item_name);};

Upvotes: 1

Mysticial
Mysticial

Reputation: 471299

You can't assign strings like that. You have several options:

class demoClass{
private:
    char *item_name;

public:

    void set_item_name(char *item_name){
        this->item_name = item_name;
    };
};

or

class demoClass{
private:
    char item_name[50];


public:

    void set_item_name(char *item_name){
        strcpy(this->item_name,item_name);
    };
};

or

class demoClass{
private:
    string item_name;


public:

    void set_item_name(char *item_name){
        this->item_name = item_name;
    };
};

Be aware that the first two of these have "gotchas" if you aren't careful.

In the first one, if the life of the pointer you pass ends before the object is destroyed. You'll get a dangling pointer.

In the second one, if your string is longer than 49 characters, you'll overrun the array.

The third one is the preferred C++ way.

Upvotes: 9

Related Questions