Error With Inputting to Dynamic Array

I'm new to dynamic memory and for some reason this doesn't work:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <new>

using namespace std;

int main()
{
    string *words1 = new (nothrow) string[0];
    cin >> words1[0];
    return 0;
}


Every time I type something and press enter the console stops working. Anyone know what I'm doing wrong?
You should try out "char" instead of "std::string". Anyway, You're not allocating memory to use.
string *words1 = new (nothrow) string[0];
You are allocating a dynamic array that can store 0 elements.
(That this doesn't make sense but is allowed anyway is a different discussion.)

You also forget to delete[] words1; at the end. This causes a memory leak.

You also forget to #include <string> at the beginning, and as a result your code is not portable. (Other people using a different compiler may get a compilation error.)

If you want to allocate a dynamic array of std::string that can store four of them:

1
2
3
4
5
6
7
8
9
#include <string>

// ...

    string *words1 = new (nothrow) string[4];

// ...

    delete[] words1;


If you want to allocate a single std::string dynamically:

1
2
3
4
5
6
7
8
9
#include <string>

// ...

    string *words1 = new (nothrow) string;

// ...

    delete words1; // not delete[]! 

Last edited on
Topic archived. No new replies allowed.