-4

I want to make auto grow a char array when the user enters any character and stop when the user press enter. I write this code but the output not correct.

char* dynamicmem(char size) {
    char* temp;
    temp = new char[size];
    return temp;
}

char* regrow(char* ptr, int size, char num) {
    char* p = NULL;
    int resize = size + 1;
    p = new char[resize];
    for (int i = 0; i < size; i++) {
        p[i] = ptr[i];
    }
    p[size] = num;
    delete []ptr;
    return p;
}
    
int main() {
    char* name = NULL;
    int size = 0;
    name = dynamicmem(size);
    cout << "Enter Name: ";
    char n='.';
    while(n!='\r') {
        n = _getche();
        name = regrow(name, size, n);
        size++;
    }
    cout << endl << name;
}

Output:

Enter Name: mohsan

²²²²▌▌▌▌▌▌▌▌▌▌▌▌▌▼U/☼▌◄
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 6
    Isn't this what `std::string` is for? – Some programmer dude Jun 24 '21 at 06:58
  • One mistake is that the char-array is not null-terminated. Putting a `name = regrow(name, size, '\0');` before printing it should fix that. – Lukas-T Jun 24 '21 at 06:59
  • 2
    It is highly advisable to use [standard library containers](https://en.cppreference.com/w/cpp/container). Also consider using `nullptr` [instead](https://stackoverflow.com/questions/20509734/null-vs-nullptr-why-was-it-replaced) of `NULL`. – rawrex Jun 24 '21 at 06:59
  • 1
    As for solving the problems with your current code, I recommend you take this as the perfect time to learn how to use a *debugger* to step through your code statement by statement while monitoring variables and their values. – Some programmer dude Jun 24 '21 at 07:00
  • @churill and how i can add new character in array?? – Mohsan Yaseen Jun 24 '21 at 07:00
  • @rawrex 'nullptr' not working properly. – Mohsan Yaseen Jun 24 '21 at 07:03
  • 1
    @churill doing another reallocation just to append the null terminator is overkill. `dynamicmem()` and `regrow()` should both allocate room for, and then insert, a null terminator into each array they create. – Remy Lebeau Jun 24 '21 at 07:05
  • @RemyLebeau I agree completely, what I suggested was a quick fix using the code OP already has. – Lukas-T Jun 24 '21 at 07:07

1 Answers1

0

You are not null-terminating the arrays you create. Try this instead:

char* dynamicmem(char size) {
    char* temp = new char[size + 1];
    temp[size] = '\0';
    return temp;
}

char* regrow(char* ptr, int size, char c) {
    char *p = dynamicmem(size + 1);
    for (int i = 0; i < size; i++) {
        p[i] = ptr[i];
    }
    p[size] = c;
    delete [] ptr;
    return p;
}
    
int main() {
    int size = 0;
    char *name = dynamicmem(size);
    cout << "Enter Name: ";
    char c;
    while (cin.get(c) && c != '\r' && c != '\n') {
        name = regrow(name, size, c);
        ++size;
    }
    cout << endl << name;
    delete[] name;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770