Solved How to type cast or convert from QString to char *
-
@SGaist
I am connecting my QT code to a standard C++ code,
here my stuct.fileNameQString contains a file path which is of QString ,
while assigning this data to the other module code like to the structure
structurechar.fileName which is of type char * (char pointer) i am getting an cast error. -
My point stays: properly allocate fileName and copy the stuff you need in there.
-
The point is very valid one, but doesn't explain the cast error.
Whenever there is an error, it is important to see the error message exactly, not just a hint that there was one. -
@SGaist
Still i am facing the same problem even after allocating the memory for the structure.
void MainWindow::on_clicked()
{structptr = ( mystruct*)malloc(sizeof(mystruct)); if (structptr==NULL) { qDebug()<<"ERROR!"; } else structptr->word=GUI_videostruct.videoFileName.toStdString().c_str();; qDebug()<<"the file name is"<<*structptr; free(structptr);
}
where strcutptr is the structure obj of mystruct * type
error: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
structptr->word=GUI_videostruct.videoFileName.toStdString().c_str();;
^ -
@kishore_hemmady What you are doing is not what @SGaist suggested. He suggested to copy the STRING.
So, copy what GUI_videostruct.videoFileName.toStdString().c_str() returns to your allocated string of same size... -
@jsulm
I am not getting it,
can you help me by the snippet please. -
size_t size = strlen(stuct.fileNameQString.toStdString().c_str()); structurechar.fileName = malloc(size); strncpy(structurechar.fileName, stuct.fileNameQString.toStdString().c_str(), size);
-
@kishore_hemmady
I believe you want to know why you get the compilation error you see?c_str()
returns aconst char*
. Note theconst
. This C-string is considered immutable, i.e. it must not be updated.You do not show your definition of
mystruct.word
, but I'm guessing that ischar *
, notconst char *
? So it is mutable.Hence the error messge.
Is that what you wanted to know about the error?
-
-
@kishore_hemmady
Have you lookedd at https://wiki.qt.io/Technical_FAQ#How_can_I_convert_a_QString_to_char.2A_and_vice_versa.3F ?Do not forget to allocate space for the final 0 of the C-string btw.