getting length of char*?

Started by
6 comments, last by samoth 15 years, 11 months ago
lets size i have char* test = "test character pointer"; Now this string is 22 characters long(maybe 23 with terminating character). Now would i be able to get the number through code?
Advertisement
http://www.cplusplus.com/reference/clibrary/cstring/strlen.html
use the strlen(char*); or, assuming that the pointer is null terminated:

int size = 0;
for(size = 0; size < some max value; size ++)
{
if(test == (char)0)
break;
}
You can also try this alternative if you're using C++:

char* test = "test character pointer";std::string str(test);std::cout << str.length(); // returns size of str
"A human being is a part of a whole, called by us,universe, a part limited in time and space. He experiences himself, his thoughts and feelings as something separated from the rest... a kind of optical delusion of his consciousness. This delusion is a kind of prison for us, restricting us to our personal desires and to affection for a few persons nearest to us. Our task must be to free ourselves from this prison by widening our circle of compassion to embrace all living creatures and the whole of nature in its beauty."A. Einstein
Quote:Original post by Great_White
You can also try this alternative if you're using C++:

*** Source Snippet Removed ***


Or you could just do:
std::string ("test character pointer").length ()
Quote:Original post by Key_46
use the strlen(char*); or, assuming that the pointer is null terminated:

int size = 0;
for(size = 0; size < some max value; size ++)
{
if(test == (char)0)
break;
}


dude, strlen requires a null terminated string,
and its the string that has to be null terminated, not the pointer.


and if you are working with char strings you should always null terminate them.




char* test = "test character pointer"; // const char strings will always be automatically null terminated
unsigned int size = strlen(test); // equals 22, null char not counted

include <string.h>, <windows.h> includes it in the background if you are working with windows.




Quote:Original post by Key_46
use the strlen(char*); or, assuming that the pointer is null terminated:

int size = 0;
for(size = 0; size < some max value; size ++)
{
if(test == (char)0)
break;
}

// alternativelyint size = 0;while (*(str++))	size++;return size;
All proposed solutions work, but using strlen() is preferrable to everything else in the given example, because the string is a string literal.

Modern compilers will simply replace strlen() with an integer literal equal to the string's length, whereas the for() construct will calculate the length at runtime, as will std::string::length (which will additionally have to allocate memory, copy the string, and free memory).

This topic is closed to new replies.

Advertisement