I was think something like:
const char * res[cnt];
int i = 0;
for (auto mystring : strings) {
const char * str = mystring.c_str();
res[i++] = str;
}
//then pass res as const char **
But it occurred to me that 'str' is a local variable, the address stored in res could be invalid? What is the right way to do so?
The problem has nothing to do with str, which will be destroyed after iteration, but this doens't mean the char array pointed by it will be destroyed too.
The problem is mystring is declared as by-copy, it'll be destroyed after iteration, then the char arrays returned by c_str get destroyed too. Pointers assigned into res become dangling.
You can change mystring as reference (to const), e.g.
for (auto const & mystring : strings) {
const char * str = mystring.c_str();
res[i++] = str;
}
Related
string b="some string another string";
std::regex r("string");
std::sregex_iterator m(b.begin(),b.end(),r);
for (std::sregex_iterator end; m!=end; m++)
{
// want a char* to m->str() in here
}
I'm gettng totally lost trying to determine what's what because of the templates. I've tried
const char *c = m->str().c_str() // compiles but points to ""
Answer
Pointed out by lightness below
const char *c = &b[m->position()]; // length of str is m->length()
const char *c = m->str().c_str()
m->str() is a temporary value, not a reference to data inside m, so c is immediately dangling.
Just store the string first:
const std::string str = m->str();
const char* c = str.c_str();
Yes, the copy is unfortunate.
A cheaper way than the copy would be:
const std::string_view sv{
b.data() + m->position(),
m->length()
};
This is great if you can use string views. But it is not null-terminated! So, if you really do need a const char*, this won't work for you and you're pretty much stuck with a fresh buffer.
I fail to convert int to a c-string (const char*):
int filenameIndex = 1;
stringstream temp_str;
temp_str<<(fileNameIndex);
const char* cstr2 = temp_str.str().c_str();
There is no error but cstr2 does not get the expected value. It is initialized with some address.
What's wrong and how can I fix it?
temp_str.str() returns a temporary object which is destroyed at the end of a statement. As such, the address pointed by cstr2 gets invalidated.
Instead, use:
int filenameIndex = 1;
stringstream temp_str;
temp_str<<(filenameIndex);
std::string str = temp_str.str();
const char* cstr2 = str.c_str();
DEMO
temp_str.str() is a temporary string value, destroyed at the end of the statement. cstr2 is then a dangling pointer, invalidated when the array it pointed to was deleted by the string's destruction.
You'll need a non-temporary string if you want to keep hold of a pointer to it:
string str = temp_str().str(); // lives as long as the current block
const char* cstr2 = str.c_str(); // valid as long as "str" lives
Modern C++ also has slightly more convenient string conversion functions:
string str = std::to_string(fileNameIndex);
const char* cstr2 = str.c_str(); // if you really want a C-style pointer
Again, this returns a string by value, so don't try cstr2 = to_string(...).c_str()
I am not able to concat two const char*.
I do the following:
const char* p = new char[strlen(metadata.getRoot())+strlen(metadata.getPath())];
strcat(const_cast<char*>(p),metadata.getRoot());
strcat(const_cast<char*>(p),metadata.getPath());
strcpy(const_cast<char*>(args2->fileOrFolderPath),p);
function(args2->fileOrFolderPath);
Now when I print the variable args2->fileOrFolderPath on the console then the correct output appears... But when I call a method with the variable as parameter, and work with the variable then I got a segmentation fault. What is the problem?
I did not declare them like this but i know they have this information
So, I have this:
const char* ruta1 = "C:\\Users\\Deivid\\Desktop\\";
const char* ruta2 = "lenaGris.xls";
Then I used this for concatenation:
char * RutaFinal = new char[strlen(ruta1) + strlen(ruta2) + 1];
strcpy(RutaFinal, ruta1);
strcat(RutaFinal, ruta2);
printf(RutaFinal);
This worked for me.
I would prefer using std::string for this, but if you like char* and the str... functions, at least initialize p before using strcat:
*p = 0;
BTW:
using std::string, this would be:
std::string p = std::string(metadata.getRoot()) + metadata.getPath();
strcpy(const_cast<char*>(args2->fileOrFolderPath), p.c_str());
function(args2->fileOrFolderPath);
And you don't have to deallocate p somewhere.
1.
const char* p=new char[strlen(metadata.getRoot())+strlen(metadata.getPath())+1];
the length plus 1 to store '\0'.
2.
strcpy(const_cast<char*>(args2->fileOrFolderPath),p);
You can not guarantee args2->fileOrFolderPath 's length is longger than strlen(p).
This works well
#include <iostream>
using namespace std;
void foo(const char*s){
cout<<s<<endl;
}
int main(int argc,char*argv[]){
const char* s1 = "hello ";
const char* s2 = "world!";
const char* p = new char [strlen(s1)+strlen(s2)+1];
const char* s = new char [strlen(s1)+strlen(s2)+1];
strcat(const_cast<char*>(p),s1);
strcat(const_cast<char*>(p),s2);
strcpy(const_cast<char*>(s),p);
cout<<s<<endl;
foo(s);
return 0;
}
You have char pointers, pointing to char constants which can't be modified . What you can do is to copy your const char array to some char array and do like this to concate const strings :
char result[MAX];
strcpy(result,some_char_array); // copy to result array
strcat(result,another_char_array); // concat to result array
I believe you need to include space for the null terminator, and the first parameter to strcat shouldn't be const as you're trying to modify the memory being pointed to.
You want to do something like this:
char * str1 = "Hello, ";
char * str2 = "World!\n";
char * buffer = malloc(strlen(str1) + strlen(str2) + 1);
strcpy(buffer, str1);
strcat(buffer, str2);
printf(buffer);
Which prints out "Hello, World!" as expected.
As for the error you're seeing when using a parameter, I've wrote some tests to see why it doesn't break when using a const local variable. While compiling using a const char * for the pointer I'm using as the target I get this warning:
./strings.c:10: warning: passing argument 1 of ‘strcat’ discards qualifiers from pointer target type
As it states, const is discarded and it works as expected. However, if I pass a parameter which is a const char * pointer, then I get a bus error when trying to modify the buffer it writes to. I suspect what is happening is that it ignores the const on the argument, but it can't then modify the buffer because it's defined as const elsewhere in the code.
char *buffer1 = "abc";
const char *buffer2 = (const char*) buffer;
std :: string str (buffer2);
This works, but I want to declare the std::string object i.e. str, once and use it many times to store different const char*.
What's the way out?
You can just re-assign:
const char *buf1 = "abc";
const char *buf2 = "def";
std::string str(buf1);
str = buf2; // Calls str.operator=(const char *)
Ah well, as I commented above, found the answer soon after posting the question :doh:
const char* g;
g = (const char*)buffer;
std :: string str;
str.append (g);
So, I can call append() function as many times (after using the clear()) as I want on the same object with "const char *".
Though the "push_back" function won't work in place of "append".
str is actually copying the characters from buffer2, so it is not connected in any way.
If you want it to have another value, you just assign a new one
str = "Hello";
Make a Class say MyString which compose String buffer.
Have a constant of that class.
and then u can reassign the value of the composed string buffer, while using the same constant.
If i pass a char * into a function. I want to then take that char * convert it to a std::string and once I get my result convert it back to char * from a std::string to show the result.
I don't know how to do this for conversion ( I am not talking const char * but just char *)
I am not sure how to manipulate the value of the pointer I send in.
so steps i need to do
take in a char *
convert it into a string.
take the result of that string and put it back in the form of a char *
return the result such that the value should be available outside the function and not get destroyed.
If possible can i see how it could be done via reference vs a pointer (whose address I pass in by value however I can still modify the value that pointer is pointing to. so even though the copy of the pointer address in the function gets destroyed i still see the changed value outside.
thanks!
Converting a char* to a std::string:
char* c = "Hello, world";
std::string s(c);
Converting a std::string to a char*:
std::string s = "Hello, world";
char* c = new char[s.length() + 1];
strcpy(c, s.c_str());
// and then later on, when you are done with the `char*`:
delete[] c;
I prefer to use a std::vector<char> instead of an actual char*; then you don't have to manage your own memory:
std::string s = "Hello, world";
std::vector<char> v(s.begin(), s.end());
v.push_back('\0'); // Make sure we are null-terminated
char* c = &v[0];
You need to watch how you handle the memory from the pointer you return, for example the code below will not work because the memory allocated in the std::string will be released when fn() exits.
const char* fn(const char*psz) {
std::string s(psz);
// do something with s
return s.c_str(); //BAD
}
One solution is to allocate the memory in the function and make sure the caller of the function releases it:
const char* fn(const char*psz) {
std::string s(psz);
// do something with s
char *ret = new char[s.size()]; //memory allocated
strcpy(ret, s.c_str());
return ret;
}
....
const char* p = fn("some text");
//do something with p
delete[] p;// release the array of chars
Alternatively, if you know an upper bound on the size of the string you can create it on the stack yourself and pass in a pointer, e.g.
void fn(const char*in size_t bufsize, char* out) {
std::string s(psz);
// do something with s
strcpy_s(out, bufsize, s.c_str()); //strcpy_s is a microsoft specific safe str copy
}
....
const int BUFSIZE = 100;
char str[BUFSIZE];
fn("some text", BUFSIZE, str);
//ok to use str (memory gets deleted when it goes out of scope)
You can maintain a garbage collector for your library implemented as
std::vector<char*> g_gc; which is accessible in your library 'lib'. Later, you can release all pointers in g_gc at your convenience by calling lib::release_garbage();
char* lib::func(char*pStr)
{
std::string str(pStr);
char *outStr = new char[str.size()+1];
strcpy(outStr, str.c_str());
g_gc.push_back(outStr); // collect garbage
return outStr;
}
release_garbage function will look like:
void lib::release_garbage()
{
for(int i=0;i<g_gc.size();i++)
{
delete g_gc[i];
}
g_gc.clear();
}
In a single threaded model, you can keep this g_gc static. Multi-threaded model would involve locking/unlocking it.