array of chars on free store

First of all this is a part of an exercise.
Is it possible to create a pointer to an arbitrarily long word stored as an array of characters on free store using new without predefining huge buffer to be sure that all the characters will fit there?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

void cpy(char* buffer, const std::string& str){
    	int i = 0;
	for (; i < str.size(); ++i) {
		buffer[i] = str[i];
	}
	buffer[i] = '\0';
}

int main(){
        
      	char* buffer = new char[1000];
	std::string str;

	std::cin >> str;

        cpy(buffer, str);

        return 0;
}


Is there better way than this? Also now I cant even store something bigger than 1000 characters not that I think I would need to very often.
Last edited on
Instead of this:
char* buffer = new char[1000];
have this:
char* buffer = new char[size_needed];

where you calculate size_needed during the programs execution.

Obviously, if this wasn't an exercise just for the fun of it, you would just use a string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <algorithm>
#include <iostream>
#include <string>

char* alloc_copy(const std::string& str) 
{
    std::size_t buffer_size = str.size() + 1;

    char* buffer = new char[buffer_size];
    std::copy(str.begin(), str.end(), buffer);
    buffer[buffer_size - 1] = '\0';

    return buffer;
}

int main() {

    std::string str;
    std::cin >> str;

    std::size_t buffer_size = str.size() + 1;
    char* buffer = alloc_copy(str);

    std::cout << buffer << '\n';
    delete [] buffer;
}
Cool, tnx a lot guys. I didn't notice that when using new, size of an array doesn't have to be a constant expression. TY very much :)
Topic archived. No new replies allowed.