Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
1.00/5 (7 votes)
See more:
C++
//finding string length using pointer and dynamic memory allocation.

// string Length
#include iostream.h
#include conio.h
#include string.h

void main()
{
int *size;
int a,n;

cout<<"Enter the memory size what ever you want: "<>a;
size = new int[a];
if(size == 0)
cout<<"Memory is not allocate: "<>str;
int count=0;
//for( str=0; *str!=0; str++)
//while(*str)
for(int i=0; str[i]!=NULL; i++)
{
count = count+1;
//str++;
}
cout<<"string Length: "
Posted
Updated 3-Oct-11 21:20pm
v2
Comments
Legor 4-Oct-11 4:35am    
Any question ?

Finding string length
C++
cout << "The size of str is " << str.size() << " characters.\n"

http://www.cplusplus.com/reference/string/string/size/[^]
 
Share this answer
 
Comments
ThatsAlok 4-Oct-11 6:11am    
this is possible only if you using string class!
Prerak Patel 4-Oct-11 6:56am    
There is no declaration shown in code so I guessed the same.
Albert Holguin 4-Oct-11 9:26am    
true... +5... :)
How could it possibly compile? There are a number of problems: non-existing operators <> (must be <<, >>), absence of any string (you probably mean char *str? where is that? undeclared variable is used), incomplete last statement of main, no variable in last line and no ';' terminator, no closing bracket in the main block… Why do you have the array int *size and how come it is called size?..

Also, you could use strlen.

Nothing to talk about. I cannot even understand how such text could be written. If you tried to copy some code without understanding, you're just wasting your time.

—SA
 
Share this answer
 
C-like strings are NULL terminated, hence, you can measure the length of the string counting characters until you find the NULL terminator. Since (in the best hypothesis: as SA pointed out, your program didn't even compile) you allocated memory for the string but didn't initialize it, the allocated memory contains garbage and so you are measuring the length of a 'garbage-string'.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 4-Oct-11 11:09am    
Unfortunately, there is no allocation of str; this variable is not even declared . Allocated is int *size -- take a look.
--SA
I suggest you first learn to write syntactically correct C++ code before asking questions about semantics.

Oh, and FYI - the output you're getting is from the compiler, complaining about your bad syntax, not from your program! This is not VB or any other interpreted language, you first have to get it syntactically right before you can try to run it. See http://www.differencebetween.com/difference-between-compiler-and-vs-interpreter/[^]
 
Share this answer
 

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