• Advertisement
Sign in to follow this  

string comparison problem

This topic is 2562 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

im wanting to compare the sizeof my string with 5 bytes and im curious on how i would do this using c++




for example




char string[5] = "poopy";

how would i check the sizeof this string? and how would i compare it's size(#of bytes) to a specific number of bytes(for example 5) -thx

Share this post


Link to post
Share on other sites
Advertisement
In C++:std::string string = "poopy";
if(string.size() == 5)
{
}
In C:char string[] = "poopy";
if(strlen(string) == 5)
{
}
Note that the C-string "poopy" is 5 characters long, but takes up 6 bytes due to the null-terminator on the end.

Share this post


Link to post
Share on other sites
C++'s standard sizeof operator will do this.
void f()
{
char s1[5];
char* s2;

cout << sizeof( s1 ) ; // Prints 5
cout << sizeof( s2 ); // Prints 4 on x86;
}

An array of five chars is also five bytes, so that's why 5 is printed. A pointer to an array is four bytes (on x86 hardware, possibly eight bytes on x64 hardware) so four is printed. Another example is necessary:
void g( char s1[5], char s2[] )
{
cout << sizeof( s1 ) ; // Prints 5
cout << sizeof( s2 ); // Prints 4 on x86;
}

If you were using an std::string, you could simply call std::string::size.

Share this post


Link to post
Share on other sites

void g( char s1[5], char s2[] )
{
cout << sizeof( s1 ) ; // Prints 5
cout << sizeof( s2 ); // Prints 4 on x86;
}


Try it:


#include <iostream>

using namespace std;


void g( char s1[5], char s2[] )
{
cout << sizeof( s1 ) ; // Prints 5
cout << sizeof( s2 ); // Prints 4 on x86;
}

int main()
{
char s1[5];
char s2[100];
g(s1, s2);
}

Point here: arrays, when passed to functions, are syntactic sugar for pointers. You can pass an array by reference, but the syntax is a little ugly:


#include <iostream>

using namespace std;


void g( char (&s1)[5], char s2[] )
{
cout << sizeof( s1 ) ; // Prints 5
cout << sizeof( s2 ); // Prints 4 on x86;
}

int main()
{
char s1[5];
char s2[100];
g(s1, s2);
}

Doing so preserves the type information (for an array, that includes the size). It also disallows incorrectly sized arrays or pointers being passed, which using an explicit size does not.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement