can any body tell me how to conver const char* to char*?
get_error_from_header(void *ptr, size_t size, size_t nmemb, void *data) {
ErrorMsg *error = (ErrorMsg *)data;
char* err = strstr((const char *)ptr,"550");
//error cannot convert const char** to char*
if(err) {
strncpy(error->data,(char*)ptr,LENGTH_ERROR_MESSAGE-1);
error->data[LENGTH_ERROR_MESSAGE-1] = '\0';
error->ret = true;
}
return size*nmemb;
}
Best Answer
There are a few things I don't understand here. I see that this is tagged for C++/CLI, but what I describe below should be the same as Standard C++.
Doesn't compile
The code you give doesn't compile;
get_error_from_header
does not specify a return type. In my experiments I made the return typesize_t
.Signature of C++
strstr()
The signature for
strstr()
in the standard C library is:but the signature for
strstr()
in the C++ library, depending on the overload, is one of:I would choose the first overload, because you don't want to modify the string, you only want to read it. Therefore you can change your code to:
Also, I'm assuming your comment reporting the error:
is a typo: there's no
const char**
to be seen.Assignment to
err
unnecessaryAs is pointed out in a previous answer, the use of
err
to store the result ofstrstr
is unnecessary if all it's used for is checkingNULL
. Therefore you could use:Use of
reinterpret_cast<>
encouragedAs is pointed out in another answer you should be using
reinterpret_cast<>
instead of C-style casts:Use of
const_cast<>
to stripconst
Given the example in the question, I don't see where this is necessary, but if you had a variable that you need to strip of
const
-ness, you should use theconst_cast<>
operator. As in:As is pointed out in a comment, the reason to use
const_cast<>
operator is so that the author's intention is clear, and also to make it easy to search for the use ofconst_cast<>
; usually stripping const is the source of bugs or a design flaw.