Sign in to follow this  

getting length of char*?

This topic is 3502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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
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
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

This topic is 3502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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