Sign in to follow this  
3dmodelerguy

getting length of char*?

Recommended Posts

Key_46    540
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[i] == (char)0)
break;
}

Share this post


Link to post
Share on other sites
Great_White    148
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

Share this post


Link to post
Share on other sites
thre3dee    100
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 ()

Share this post


Link to post
Share on other sites
Molle85    172
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[i] == (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.




Share this post


Link to post
Share on other sites
thre3dee    100
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[i] == (char)0)
break;
}

// alternatively
int size = 0;
while (*(str++))
size++;
return size;

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this