Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string and const char* and .c_str()?

Tags:

c++

string

I'm getting a weird problem and I want to know why it behaves like that. I have a class in which there is a member function that returns std::string. My goal to convert this string to const char*, so I did the following

    const char* c;
    c = robot.pose_Str().c_str();  // is this safe??????
    udp_slave.sendData(c);

The problem is I'm getting a weird character in Master side. However, if I do the following

    const char* c;
    std::string data(robot.pose_Str());
    c = data.c_str();
    udp_slave.sendData(c);

I'm getting what I'm expecting. My question is what is the difference between the two aforementioned methods?

like image 323
CroCo Avatar asked May 05 '14 03:05

CroCo


People also ask

What is string c_str ()?

The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object.

What is the difference between const char * and string?

1 Answer. Show activity on this post. string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.

What does c_str () mean in C++?

The c_str() method converts a string to an array of characters with a null character at the end. The function takes in no parameters and returns a pointer to this character array (also called a c-string).

What is c_str () in Arduino?

Description. Converts the contents of a String as a C-style, null-terminated string. Note that this gives direct access to the internal String buffer and should be used with care.


2 Answers

It's a matter of pointing to a temporary. If you return by value but don't store the string, it disappears by the next sequence point (the semicolon).

If you store it in a variable, then the pointer is pointing to something that actually exists for the duration of your udp send

Consider the following:

int f() { return 2; }


int*p = &f();

Now that seems silly on its face, doesn't it? You are pointing at a value that is being copied back from f. You have no idea how long it's going to live.

Your string is the same way.

like image 169
Dov Avatar answered Sep 17 '22 01:09

Dov


.c_str() returns the the address of the char const* by value, which means it gets a copy of the pointer. But after that, the actual character array that it points to is destroyed. That is why you get garbage. In the latter case you are creating a new string with that character array by copying the characters from actual location. In this case although the actual character array is destroyed, the copy remains in the string object.

like image 26
Rakib Avatar answered Sep 18 '22 01:09

Rakib