简体   繁体   中英

Remove C++ char* has point address

Since I changed my project settings, the boolean value below returns false because in the debugger, value of the char* parameter contains pointer address. how do i remove this?

I created this simple example to illustrate (i have to keep char* data type) and I can't do pattern matching to remove the pointer address.

void Test(char* thisValue) 
{
if (thisValue == "PassingTest")
{
bo = true;
}
else
{
bo = false;
}
}

In debugger, I found thisValue = " PassingTest"

Please guide how to let thisValue only contain "PassingTest" as a value and not pointeraddress.

That's how char*s work - they're pointers to characters in memory. If you want a string that supports values you can use std::string from #include <string> .

Working with char*s, you can use

if (strcmp(thisValue, "PassingTest") == 0)

and if you're not intending to modify the string contents in your function you can accept const char* thisValue rather than just char* thisValue .

The == operator cannot compare string values in C; it can only compare their pointers. Use the strcmp function to test whether two strings are equal (it returns 0 if they are).

if (thisValue == "PassingTest")

This will not work, as thisValue is char* .

Use std::string :

if (std::string(thisValue) == "PassingTest")

It will work now.

It will be better if you do this:

void Test(const std::string & thisValue) 
{
    bo = (thisValue == "PassingTest") ;
}

You have no guarantee that two identical literal strings will reside at same memory address.

If they do then that's an example of "constant folding", which is an optimization that may or may not be done.

So your code has arbitrary result.

To avoid this problem, just use std::string instead of raw pointers and raw arrays.

Like

void test( std::string const& thisValue )
{
    bo = (thisValue == "PassingTest");
}

Cheers & hth.,

In C use strcmp(3) . C++ has nice std::string for this.

The reason why is that in C++ the comparison in the if block is comparing pointer addresses not string values. To compare the actual string values you'll need to use a function like strcmp or even better use STL string values

void Test(const stl::string thisValue) {
  if (thisValue == "PassingTest") {
    bo = true;
  } else { 
    bo = false;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM