Home > OS >  Problem with dynamic array in constructor, cannot convert char* to char
Problem with dynamic array in constructor, cannot convert char* to char

Time:09-13

I can't use string because of task conditions, so it must be char*. There is problem with dynamic array in constructor. Error "'=': cannot convert 'char*' to 'char'"

#include <iostream>

class Line {
public:
    const int Size = 10;
    char* DynamicLines = new char[Size];
    int counter = 0;

    Line(char* otherline) {
        if (counter < Size) {
            DynamicLines[counter] = otherline;
            counter  ;
        }
        std::cout << "constructor called\n";
    }

    ~Line() {
        delete[] DynamicLines;
        std::cout << "destructor called\n";
    }

    void Print();
};

void Line::Print() {
    this->counter = 0;
    std::cout << DynamicLines[counter] << "\n" << "length = ";
    counter  ;
}


void main()
{
    char* temp = new char;
    std::cin >> temp;
    Line Fline(temp);
    Fline.Print();
    delete temp;
        
    system("pause");
}

CodePudding user response:

According to the C Standard the function main shall have the return type int

int main()

In this constructor

Line(char* otherline) {
    if (counter < Size) {
        DynamicLines[counter] = otherline;
        counter  ;
    }
    std::cout << "constructor called\n";
}

this statement

DynamicLines[counter] = otherline;

does not make a sense. In the left hand side of the assignment there is an object of the type char while in the right hand side there is an object of the type char *. So the compiler issues the error message.

You need to copy elements of one array into another array.

Also the condition of this if statement

if (counter < Size) {

always evaluates to true. So the statement also does not make a sense.

And in main this code snippet can result in undefined behavior because you allocated only one character

char* temp = new char;
std::cin >> temp;

but are trying to enter a string.

CodePudding user response:

char *DynamicLines is pointer to an array of char. Therefore each entry in the array, is a char, not a char* (pointer).

Your constructor accepts a pointer to char which needs to be dereferenced, in order to access the char in the memory and store it in the array.

So:

Line(char* otherline) {
    if (counter < Size) {
        DynamicLines[counter] = *otherline; // Notice * in front, to get the value from the pointer
        counter  ;
    }
    std::cout << "constructor called\n";
}
  • Related