*correction
Please add 1 in n_itr in the above code.
strlen() returns the length of string not including the '\0' (null) character.

Salem commented: correction - get a time machine and read this -> http://www.daniweb.com/software-development/cpp/threads/78223 -4
int string::getsize()
{
	int n_itr=strlen(this->arr)+1;  //strlen does not include null character
	n_itr*=sizeof(char);
	return n_itr;
}

Here string is my own class and contains only one data member char* arr which is being used to dynamically create an array.
getsize() returns the size of this array in bytes.

Hope this helps

>>n_itr*=sizeof(char);

Not needed. The C/C++ standard guarantee that sizeof(char) is always 1. so that statement is merely multiplying n_itr by 1, which is nonsense.

And what is that string class you posted? Are you referring to std::string? If yes, then it has no arr data and that makes your complete post nonsense.

Just out of curiosity, there is a very dangerous and non-portable way to do it, but works on Visual Studio. This specific compiler, keeps a "header" of the dynamic memory. So we need just to go back 16 bytes and read the number of bytes pointed by the allocated memory. If you need the number of elements, you must divide the total size by size of each element. Here's a snippet:

short* p = new short[512];
int size = *(int*)((char*)p-16);
int elements = size / sizeof( short );

There are other non-portable ways, but much safer.
On Windows, you can use a function called _msize(void*) (malloc.h)
On Linux, it is possible to use malloc_usable_size(void*) (check malloc_np.h for additional info), but i've never tryed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.