c++ - 如何在 C++ 中使用 new[ ] 和 delete[ ] 运算符

标签 c++ dynamic-memory-allocation

我目前正在学习 C++,我已经完成了这项事件,我需要将数组从大写字母转换为小写字母,反之亦然:

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;

}

但他们要我使用 new[] 和 delete[] 运算符,所以我将不再声明数组中的数字,这部分是 char str[100]; ,我已经尝试使用它,但这个概念让我感到困惑。

有什么建议吗?任何帮助都感激不尽!提前致谢!

最佳答案

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;
}

使用 new 可以在堆上分配内存,使用 delete[] 可以释放内存。

注意:您必须指定 sz + 1 作为数组的大小,因为 getline0 字符 放在末尾。 p>

关于c++ - 如何在 C++ 中使用 new[ ] 和 delete[ ] 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53039655/

相关文章:

C动态内存/C字符串

c - c中的内存重新分配

C++ 流如何为输入分配空间?

c++ - 如何从处于低功耗状态的 USB 设备获取字符串描述符?

c++ - 带有 C++ 模板的虚假 "use of local variable with automatic storage from containing function"?

c++ - Microsoft C++ 编译器有错误吗?

c++ - 当我需要多态性时,如何避免动态分配?

python - 从 python 调用 c++ 函数

c++ - 定义 : is there a way to expand arguments?

c - 如何为矩阵中的特定元素动态分配内存?