K
karthik.naig
Hi,
This was the routine I wrote earlier to convert a C++ string to a
char array.
But I found that the char* array consisted only of junk after returning
from the below function.
int convertStringToChar(string& str, char* data)
{
data = (char*)malloc(str.length() * sizeof(char));
memset((void*)data,0,sizeof(data));
strcpy(data,str.c_str());
return 0;
}
However, I replaced it with the following function and it worked just
fine.
int convertStringToChar(string& str, char** data)
{
*data = (char*)malloc(str.length() * sizeof(char));
memset((void*)*data,0,sizeof(data));
strcpy(*data,str.c_str());
return 0;
}
1. Can you tell me the reason?
2. Is the second routine defect free? Note that I'm not terminating the
char* array with a "\0" anywhere.
FYI, the compiler being used is gcc 2.96.
Thanks and Regards,
Karthik.
This was the routine I wrote earlier to convert a C++ string to a
char array.
But I found that the char* array consisted only of junk after returning
from the below function.
int convertStringToChar(string& str, char* data)
{
data = (char*)malloc(str.length() * sizeof(char));
memset((void*)data,0,sizeof(data));
strcpy(data,str.c_str());
return 0;
}
However, I replaced it with the following function and it worked just
fine.
int convertStringToChar(string& str, char** data)
{
*data = (char*)malloc(str.length() * sizeof(char));
memset((void*)*data,0,sizeof(data));
strcpy(*data,str.c_str());
return 0;
}
1. Can you tell me the reason?
2. Is the second routine defect free? Note that I'm not terminating the
char* array with a "\0" anywhere.
FYI, the compiler being used is gcc 2.96.
Thanks and Regards,
Karthik.