E
errfet
Hello everybody 
I needed any method of conversion std::string to char*. I found some
useful library functions, and in order to make conversion i had to
write some code for example:
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char **argv)
{
string str = "hello";
char *dst ;
dst = new char [str.size()+1];
strcpy(dst, str.c_str());
int size= (str.size()+1);
for(int i=0;i<size;i++) cout<<endl<<"char: "<<dst;
cout<<endl;
delete dst;
return 0;
}
In other words, i had to create new char[ ], execute strcpy()
function, everytime i wanted conversion... so i thought, why not to
put these instructions into one function?
I`ve writed some code :
#include <iostream>
#include <cstring>
using namespace std;
int str_to_char (char * dst, const string &str){
dst = new char [str.size()+1];
strcpy(dst, str.c_str());
return (str.size()+1);
}
int main(int argc, char **argv)
{
string str = "hello";
char *dst ;
int size = str_to_char(dst,str);
for(int i=0;i<size;i++) cout<<endl<<"char: "<<dst;
cout<<endl;
delete dst;
return 0;
}
It stopped working. Program ends with memory acces violation.
Could anyone tell me WHY? I guess it`s related to char * dst.
Cheers
I needed any method of conversion std::string to char*. I found some
useful library functions, and in order to make conversion i had to
write some code for example:
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char **argv)
{
string str = "hello";
char *dst ;
dst = new char [str.size()+1];
strcpy(dst, str.c_str());
int size= (str.size()+1);
for(int i=0;i<size;i++) cout<<endl<<"char: "<<dst;
cout<<endl;
delete dst;
return 0;
}
In other words, i had to create new char[ ], execute strcpy()
function, everytime i wanted conversion... so i thought, why not to
put these instructions into one function?
I`ve writed some code :
#include <iostream>
#include <cstring>
using namespace std;
int str_to_char (char * dst, const string &str){
dst = new char [str.size()+1];
strcpy(dst, str.c_str());
return (str.size()+1);
}
int main(int argc, char **argv)
{
string str = "hello";
char *dst ;
int size = str_to_char(dst,str);
for(int i=0;i<size;i++) cout<<endl<<"char: "<<dst;
cout<<endl;
delete dst;
return 0;
}
It stopped working. Program ends with memory acces violation.
Could anyone tell me WHY? I guess it`s related to char * dst.
Cheers