Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;使用动态数组将小写改为大写_C++_Pointers_Dynamic Arrays - Fatal编程技术网

C++ C++;使用动态数组将小写改为大写

C++ C++;使用动态数组将小写改为大写,c++,pointers,dynamic-arrays,C++,Pointers,Dynamic Arrays,我正在尝试使用动态数组将小写单词更改为大写单词。我遇到了一个我以前从未遇到过的叫做“堆损坏”的问题。有人能向我解释一下我做错了什么,并可能帮助解决这个问题吗 #include <iostream> #include <cctype> #include <new> #include <string> using namespace std; int main() { int i; int w; char *p; st

我正在尝试使用动态数组将小写单词更改为大写单词。我遇到了一个我以前从未遇到过的叫做“堆损坏”的问题。有人能向我解释一下我做错了什么,并可能帮助解决这个问题吗

#include <iostream>
#include <cctype>
#include <new>
#include <string>
using namespace std;

int main()
{
    int i;
    int w;
    char *p;
    string str;

    cout << "Change lowercase to UPPERCASE!" << endl;
    cout << "Enter Word: ";
    cin >> str;
    w = str.length();

    p = new (nothrow) char[w];

    if (p == nullptr)
        cout << "Error: memory could not be allocated" << endl;
    else
    {
        cout << "Re-Enter Word: ";
        cin >> p[w];
        for (i = 0; i < w; i++)
            cout << static_cast<char>(toupper(p[i]));
        cout << endl;
    }

    delete[] p;

    cout << "Press <Enter> to Exit";
    cin.get();
    return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
int i;
int w;
char*p;
字符串str;

cout不需要使用
char*
转换为大写。相反,您可以使用如下方法:

transform(str.begin(), str.end(), str.begin(), ::toupper);
cout << str << endl;

你犯了这么多错误,但要回答你的问题:

p = new (nothrow) char[w + 1];
这是为了给空终止字符('\0')留出空间

并使用:

cin >>  p;

使用
std::string
而不是
char*
。这将使您的生活更加轻松。
cin>>p[w];
访问
p
超出范围。您只读取一个字符,然后将其写入超出范围。即使您“修复”输入-
cin>>p
-
p
太小了一个字符。有没有办法通过动态数组来实现?我正在尝试掌握指针和动态内存的概念。我将更多地使用transform。我忘记了\0。@Podis:无论变量驻留在哪里,技术都是一样的。
transform
函数不关心容器是本地定义的(堆栈)、动态分配的(堆)还是自动变量。
cin >>  p;