Click here to Skip to main content
15,916,462 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Consider the below fragment of code :

C++
char * str = nullptr;
str = new char[sz]         


Here 'sz' is to be sought by the program during runtime.

My question is : How to find the size of str ? Neither sizeof() operator nor strlen() function work.
Posted

The size of the str will equal sz. strlen won't work because it loops until it finds the null string terminator '\0'. Since you've got a new char array, all the characters are probably '\0'.

Maybe you aren't explaining it very well, is "sz" being passed into a function, or are you trying to find out what value to assign to sz? sz should be an integer value greater than 0.
 
Share this answer
 
Comments
CPallini 20-May-13 16:52pm    
5.
Andreas Gieriet 20-May-13 17:28pm    
The allocated memory will most likely be random data and not all '\0'. C++ base types have no implicit initial value (unlike other languages like Java and C#). So, if the str variable comes from outside, there is no way to determine its allocated capacity. See also my solution #2 for alternative data structures that allow to properly handle capacity and actual stored data length.
Cheers
Andi
compuknow 20-May-13 22:33pm    
I am trying to get the size of a file as sz.
Will it work if create a clone of strlen with a difference only that it checks for the eof character?
I regard using char* str = new char[sz]; as deprecated/anachronistic.
If you do string handling, try using std::string str = ...; or if you work on raw memory try using std::vector<char> mem;. Both are smart enough to handle the dynamic memory in a decent way, i.e. you do not have to care about new/malloc/calloc/strdup/... and delete/delete[]/free/...
See http://www.cplusplus.com/reference/string/string/[^] and http://www.cplusplus.com/reference/vector/vector/[^].

Cheers
Andi
 
Share this answer
 
v2
Comments
compuknow 20-May-13 22:40pm    
Are vectors useful to store entire file content of a binary file? May be using a read command.
Andreas Gieriet 21-May-13 4:26am    
See the first solution in How to copy a file into a vector? (C++).
Cheers
Andi
PS: Vectors are very useful in managing binary dynamic data arrays.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900