cpp-how to get only the value of c_str() [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
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?

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;

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.

Related

C++ adding chars to a pointer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
From my understanding a string is just an array of char, so if i have a pointer reference to some char values shouldn't I be able to do:
*dest = "char"
However that doesn't work i have to do:
*dest = 'c';
*dest = 'h';
*dest = 'a';
*dest = 'r';
so if i have a pointer reference to some char values shouldn't I be able to do:
*dest = "char"
No, you shouldn't be able to do so.
*dest is a char. A single char object can only hold a single char object. A string is an array of characters. You cannot assign a string to a char.
However, if you had a pointer reference to some const char values, then you could assign the pointer like this:
dest = "char"
This would make the referred pointer to point to the string literal. However, this is different from *dest = 'c'; *dest = 'h'; .... The pointer assignment modifies the pointer and keeps the previously pointed characters unmodified, while assigning to the pointed character modifies the pointed characters, while keeping the pointer unmodified.
I'm guessing that by 'string' you ment a C-style string, so a char*
*dest = "char"
From what you said, dest is a char&*, when you dereference it, you get a char, type of "char" is const char*, so you're trying to assign a const char* to a char, which is a compile time error.
You should use std::string, which will enable you to do the assignment you described above, and also allocate and free memeory for you.
std::string dest = "char";

Assigning string* to char* c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to read a file in c++ and save every line(in a vector) as i will be processing them later.
I also need to save a vector of char* that will point to the first position of each string*.
The problem is that I don't know how to assign the string* to char*.
FYI, i can not use const char*, it has to be char*.
Code:
void ClassA::readFile() {
std::ifstream file("test.txt");
std::string* str = new string();
while (std::getline(file, *str))
{
_aVector.push_back(*str);
char *c = &str[0]; <-- This works if string is not declared as string*
char *c = .... <--What is the equivalent for string*
str = new string();
someFunction(c); <-- This function saves the *c in a vector.
}
}
Though the std::string protocol gives you access to the underlying memory, e.g. by calling member c_str(), these pointers are all const. If you cast it to a non-const pointer, you risk undefined behaviour if a function beyond your control then modifies the content through such a pointer.
Since C++17, the data-method gives you access to a non-const pointer to the underlying data.
Anyway, note that a string-object will - again beyond your control - replace the underlying memory if necessary, and your pointers might become invalid then. So I'd say that it's generally not a good idea to store pointers to the contents of string objects.
The only way to get a char*-pointer to the contents of an std::string I see is to copy the contents of the string, e.g. by using strdup. Thereby you avoid undefined behaviour from unintended modifying access, and you decouple the char* from the memory managed by the string object.
See the following code illustrating this:
int main() {
std::vector<std::string> aVector;
std::ifstream file("test.txt");
std::string str;
while (std::getline(file, str))
{
aVector.push_back(str);
char *c = strdup(str.c_str());
someFunction(c); // <-- This function saves the *c in a vector.
}
}

How is a const char* not a just a character? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm really confused about this because personally, I come from a java background, and recently began c++. So, I learnt all the basic stuff, like, printing stuff out to the screen and whatnot, and now, I learnt POINTERS. So, the person on youtube (The Cherno's C++ Pointer tutorial This was not the video where he declared the const char*, just the pointer tutorial that I followed.) I've been following was using this following statement to declare what I know as a 'string'.
const char* str = "random text here";
But, how is a char* converted into a string, and its even using the double quotation marks like a string! Also, what does a constant have to do with any of this? If I remove the const from my code it gives me an error. But, I understand what a pointer is. It is a variable that holds the memory address of another variable, so if one was to access that variable directly, they would just have to do *ptrVarName and dereferenced it. But how can a string "like this one" be a memory address?
Wouldn't I have to do something like this?
char[] str = "string here";
and THEN do:
char* stringPointer = *str;
(WARNING: untested code!)
Thanks in advance.
(oh and sorry if this is a really NOOBY question or the question is poorly constructed, I've just started out with c++ and stackoverflow)
EDIT: Ok, so I understand what the char* str means. It means that when you reference *str, it means that you're accessing the first character in memory. Ok, I get it now. But, what does const mean?
const char* str = "random text here";
On the right hand side, the "random text here" defines a string literal which actually is an array of type const char[17] (including the null terminator character). When you assign that array to const char* str it decays to a pointer that points to the first character. You cannot modify the string literal through the pointer because string literals are stored in read-only memory, so the following would be illegal: str[0] = 'x';
char[] str = "string here";
This one is different. It defines the char array str which has the same size as the string literal on the right hand side (const char[12]). The string literal will be copied into the array str, so you will be able to modify str. In this case, it would be legal to write str[0] = 'x';.
If you declare const char* sth ="mystring"
It will place mystring inthe memory and sth pointing to that its work like array but with direct access to memory
These are plain C-strings. A C string is always null terminated. In other words- it has '\0' at the end. So you need only the place in memory where the string starts and you can find when it ends.
For pointer arithmetic these [] brackets are only syntax sugar. str[] is the same as *str and str[1] is the same as *(str+1) only incrementing the pointer by one char (8 bits) and getting the address of the second element.
C doesn't really have strings. A string is an array of characters, terminated by a nul (0). Now arrays and pointers in C are closely linked, and a char * or const char * usually points to a string, but only in the same way as other pointers usually point to arrays. An individual char * might only point to a single character, you have to know from context, just as an int * might point to one integer or an array of integers.
Because strings are handy, there's a special syntactical rule for strings literal. A string literal in quotes becomes a const char * (in fact its type is char * for backwards compatibility). So in this sense, C has strings. But all that is happening is that the string is being laid out in the data section of the program, then its address taken.

C++ writing to std::string* var from file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Actually I'm experiencing a problem with saving single char to string*. I've got a function like this:
void save(std::string* x, const std::string& file);
Actually I'm taking each digit from the file using loop and assign it to char ch;
So, the question is how can I append this char to string*? If I make temp string and add each symbol to this string and after just do strcpy or just x = temp, I'm getting segmentation fault.
Would you tell me how to deal with this?
Thank you.
You should never directly alter a std::string's buffer, because it has its own method of managing the memory.
Instead, you should use the append() method:
char temp;
//...
if(x) //check for nullptr
{
x->append(1, temp); //appends the char 'temp' once
}
It sounds like you're creating a local string and then assigning it to x - something like this:
std::string temp;
// Add to temp
// ...
x = &temp;
The problem with this is that x is effectively an out parameter and you're assigning it to a local. When the function goes out of scope the local (temp) will be destroyed, and x will now point to the destroyed region of memory. This will give you an access violation.
You're best bet is change save so that it returns the string. Something like this:
std::string save(const std::string &file)
{
std::string temp;
// Do stuff...
return temp;
}
Now the string will be correctly copied (or moved if you're C++11) back to the caller. You can use push_back to append characters to temp.
If you don't want to return the string then pass a reference to a user supplied string and fill that:
void save(std::string &x, const std::string &file)
{
char temp;
x.push_back(temp);
}
and then call it like this:
std::string output;
save(output, "path/to/my/file);

C style character using const pointer returns incorrect result [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can a local variable’s memory be accessed outside its scope?
I've declared a C style array using pointer, and assign it a value returned by a function.
1.const char* str = chArr->readString();
Right after above, I want to cout the str as follow:
2.cout << "pointer to char is = " << str <<endl;
and the readString is:
char* CharArray::readString()
{
std::cout << "Insert a string of max 19 length:" <<std::endl;
char string[20];
std::cin.getline(string,20,'\n');
return string;
}
When I put a break point on line 2, I can see the correct result as value of str.
But the console window shows nothing, and after passing step 2, when I look at the str value, it shows something like "P÷7" or "äû:",..
Maybe worth saying that for the str I strings with length of 4,5. Not 19 despite the length of str.
You are returning a pointer to a local variable. The memory address of this variable is made available again by the system after the function ends. So it is possible that some other code overwrites it with some random data and that's why you are seeing gibberish.
In order to safely do this, use:
char* string = new char[20];
Remember to delete [] it afterwards.
You are returning the address of a local variable, the memory for which will be reused by something else after exiting the function. You are far better off returning a std::string instead like this:
std::string CharArray::readString()
{
std::cout << "Type a string and hit enter:" << std::endl;
std::string str;
std::getline(std::cin, str);
return str;
}
This also means that you don't need to worry about the maximum length (at least you don't need to worry at this point, you may have other restrictions you wish to impose elsewhere) and the memory allocations will be managed for you automatically.
You create string within the scope of readString. When you return, your string will be destroyed. You have to alloc your string in your function char *string = new char[20]; if you want to avoid this behavior.