size of memory on the heap

Hi guys so after a bit of googling I have found that there is pretty much no way to find the size of memory of an array in the heap

for example I dynamically allocated a char array and I want to find the size of the array on the heap

obviously I can't do sizeof(array) because this will just give me the size of the pointer not the array

so what I came up with is I have a size int and for every character added to my array I increment it by one since a char is one byte,I start it off at 1 to take into consideration the terminating character

anyway is this a practicle solution? if not how would I do this or how would I change my code to achieve this,also if there is any other ways to find the size out I'd love to hear.

note I know this can be done by just using std::string but I want to try work around this well I am kind of cheating because I am using a string to get the input but apart from that I want to see if this is possible

my end goal is to copy that string to a primitive char string or like an old c style string and there probably is about a 100 better ways of doing this,I'm just trying to get this way to work

thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  string input;

	int i = 1;
	char *string = new char[1];
	cout << "enter a string" << endl;
	int size = 1;
	getline(cin, input);

	string = new char[input.length()];

	for (int i = 0; i < input.length(); i++) {

		string[i] = input.at(i);
		size++;
	}
	for (int i = 0; i < input.length(); i++) {

		cout << string[i];
	}

	cout << endl;
	
	cout << size;
You're right that there is no way to get a size of a dynamically allocated array
You might wonder how does delete[] even know how much memory to free in that?
Well, the size is actually stored and delete[] uses that, but there is no way to fetch this information.

As for your question, it appears you want to copy the contents of a std::string to a char[].
So why do you even need to fetch the size? You already know what the size is going to be: input.length().
Thus there is no need to change the size either.
1
2
3
4
5
6
7
8
std::string input = "The quick brown fox jumps over the lazy dog";
char* str = new[input.length()];
for (int i=0; i<input.length(); ++i) {
   str[i] = input[i];
}
for (int i=0; i<input.length(); ++i) {
   std::cout << str[i];
}

Note: If you were trying to populate the str from a source of unknown length (e.g. a stream) this would have been an entirely different story. But you know the size in this case.
Last edited on
Hello adam2016,

Line 9 When you create the array with new you know the size of the array with "input.length()". If you will need that size later just store "input.length()" into a variable.

Hope that helps,

Andy
Topic archived. No new replies allowed.