How to use new[ ] and delete[ ] operator in C++

I’m currently learning C++, I already did this activity which I need to convert the array from uppercase to lowercase vice versa:

int main()
{
    char str[100];
    cout << "Enter anything: ";
    cin.getline(str, 100);

    //upper to lower vice versa
    for (int i = 0; i < 100; i++) {
        if (str[i] == 0x20)
        {
            continue;
        }
        str[i] ^= 0x20;
    }
    cout << "output: " << str;

return 0;

}

But they want me to use new[] and delete[] operator so I will no longer declare the numbers in array which is this part char str[100]; , I already tried to use it but the concept makes me confuse.

Any suggestion? any help will be much appreciated! Thanks in advance!

int main(){
    char *str;
    int sz = 0;

    std::cout << "enter number of characters: ";
    std::cin >> sz;

    str = new char[sz + 1];

    std::cout << "Enter anything: ";
    std::cin.ignore();
    std::cin.getline(str, sz + 1);

    //upper to lower vice versa
    for (int i = 0; i < sz; i++) {
        if (str[i] == 0x20)
        {
            continue;
        }
        str[i] ^= 0x20;
    }
    std::cout << "output: " << str;

    delete[] str;
    return 0;
}

With new you allocate memory on the heap, with delete[] you deallocate the memory.

Note: you have to assign sz + 1 as the size of the array since, the getline puts the 0 character at the end.

Read this article to clear the concept better.

3 Likes