-3

I have a function which return const char*. In this function I have the following params:

string str;

For converting str to const char* I use str.c_str().

When I debug I notice that str.c_str() contains something (I guess its address) before the value of the string. For example: If str="0" I str.c_str() wiil 0x68d5f9 "0". Why is it? How can I get only the value of the string?

sara8
  • 199
  • 3
  • 11

2 Answers2

1

This is not a problem, this is how pointers work.

Pointers point to data contained at some memory address and the debugger shows you that this pointer points to address 0x<something> and the value at this address is '0'. Nothing odd here.

When you print this value you got from str.c_str(), you'll get an ordinary C string.

cout << str.c_str();

This will give you the same as cout << str;

ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

You wouldn't get the address pointed to by the pointer in the string returned by c_str. It is a debugger artifact designed to let programmers inspect the address along with the value.

However, returning the result of c_str may be undefined behavior if the call is made on a function-scoped string.

For example, this is illegal:

const char *illegal_return() {
    string s = "quick brown fox";
    return s.c_str(); // <<== Return of c_str from a local string
}

The best fix is to return a string. If you would like to return a char pointer instead, you need to make a copy:

char *legal_return() {
    string s = "quick brown fox";
    const char *ptr = s.c_str();
    size_t len = strlen(ptr);
    char *res = new char[len+1];
    strcpy(res, ptr);
    return res;
}

The caller of the above function must call delete[] on the result to avoid memory leaks.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523