Using a const void* with string [closed] - c++

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 10 months ago.
Improve this question
In c++11, I have a function that takes a const void* data and a size_t dataSize, so I have to pass to the function the pointer to a string.
function_test( const void* Data, size_t DataSize)
{
std::string received_data((const char*)Data, DataSize);
if (received_data=="1")
{
//do stuff... I need enter here
}
}
I use:
std::string test1 = "1";
function_test(&test1, sizeof(test1));
I expect that received_data is equal to "1" but it's not, why? How can I fix this?

Why test3 is not "1"?
Because std::string is not an array of char. A pointer to std::string is not a pointer to the buffer that std::string class manages where the content of the string is stored. When you reinterpret a pointer to a std::string object as a pointer to char, you get a meaningless representation of the internals of the std::string object.
I need that test3 is equal to "1"
Then use the copy constructor:
std::string test3(test1);
P.S. Don't use C-style casts. Use C++ style static_cast etc. This will make it easier to understand the program that you are writing.

Assuming you need to pass a const void* to a legacy C-style API, you need to use:
std::string test;
reinterpret_cast<const void*>(test.c_str());

C++ is not C.
What you show is close to the following C snippet:
char test1[] = "1";
const void* test2 = test1; // test1 decays to a pointer
char test3[sizeof(test1)];
strcpy(test3, test2);
But a C++ std::string is a complex container with internal data for housekeeping and an array of characters accessible through the data or c_str method:
std::string test1 = "1";
const void* test2 = test1.c_str();
std::string test3(static_cast<const char*>(test2), sizeof(test1));

Related

Send an array of Characters as a parameter to a function in C ++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have a function that receives two parameters: one input and one input/output, the first is a constant type string and the second is a reference to an array of unsigned char characters, the problem is that when I pass the address of the array, it generates this error when compiling initial value of reference to non-const must be an lvalue
This is the code where I call the function:
unsigned char in[20];
string str = "ABCDEF123456";
function(str, &in); //ERROR HERE
And this is the function:
void function(const std::string &str, unsigned char *&in)
{
in = new unsigned char[str.length() / 2];
for (int aux = 0, tam_str = str.length(); aux != tam_str; aux += 2)
{
std::stringstream ss;
ss << std::hex << str.substr(aux, 2);
int valor;
ss >> valor;
in[aux / 2] = valor;
}
}
NOTE: The purpose of the function is to convert the content of the variable str (hexadecimal values) to the array of characters in.
The type of the argument declaration, and the type of the object that you pass do not match.
Answer for new question:
Like in the old version, you pass a pointer to an array of 20 unsigned char. But the argument type is a reference to a pointer to a unsigned char. That doesn't work.
To call the function, you must have a pointer to an unsigned char:
unsigned char* ptr = in;
function(str, ptr);
On the other hand, it makes no sense to pass a pointer by reference unless you modify the pointer - which you don't do. So, it might be more sensible to pass a copy of the pointer instead:
void function(const std::string &str, unsigned char *in);
function(str, in);
Old answer:
void function(const std::string &str, std::vector<unsigned char> &in)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
unsigned char in[20];
^^^^^^^^^^^^^^^^^^^^
function(str, &in); //ERROR HERE
^^^
The function has been declared to accept a reference to a std::vector<unsigned char> object. You attempt to pass an address to an array of 20 unsigned char as the argument. That doesn't work.
To call the function, you need to have a vector object:
std::vector<unsigned char> in;
function(str, in);

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 to pass "char* a" to "const char*"? [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 6 years ago.
Improve this question
Could you tell me the way to pass the value (char * a) to the value (const char* b)?
For example,
char * str = "Tokyo";
const char *;
"char = str" is OK?
char * str = "Tokyo";
In c++, this is not allowed †. You may not assign a const array (such as a string literal) to a non-const pointer.
const char *;
This is not allowed, because a variable declaration must have a name (unless it's a function argument).
const char *str = non_const_pointer_or_array;
The above is OK in c++.
† Implicit conversion from const to non-const is allowed in c but typically discouraged by compiler warnings. It was deprecated in c++ and not allowed at all since c++11.
In c++, it should just work. Native/Builtin types are automatically convertible to more const, but not to less const.
Therefore:
void foo(const char*) {
}
int main() {
char s[] = {'x', 'y', 'z', '\0'};
foo(s); //Compiles fine.
return 0;
}
This compiles fine, however the other way around, one has to use a const_cast. One should however not lie to the compiler and indicate that something is non const, while in actual fact it is const, as the program behavior in that case is undefined (one cannot know what the behavior of the program might be). const_cast is typically only used when old APIs require char* arguments despite it not modifying the arguments, and should never be used to "lie" to the compiler.
Example:
void some_old_api(char*){}
int main() {
const char* cs = "xyz";
some_old_api(const_cast<char*>(cs));
return 0;
}
A character array hard-coded in your program is a const char*, so you can declare it as const char* str = "Tokyo";Or, when you do have a char* str, you can cast it as follows: const char* myconst = (const char*) str;

cpp-how to get only the value of c_str() [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 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.