const char to char problem
How do I convert from char
to const char
? How do I implement type casting without changing the char SendBuf
? Here is my code:
.cpp
// main()
char SendBuf[6] = "Hello";
sendto(..., SendBuf, ...);
// sendto structure
int sen开发者_StackOverflow中文版dto(
__in SOCKET s,
__in const char *buf,
__in int len,
__in int flags,
__in const struct sockaddr *to,
__in int tolen
);
Error
Error 1 error C2440: '=' : cannot convert from 'const char [6]' to 'char [6]'
Thank you.
I don't have a Microsoft compiler handy to test this theory, but I suspect that the OP has code like this:
int main() {
char SendBuf[6];
SendBuf = "Hello";
// sendto(..., SendBuf, ...);
}
I suspect that the error he is seeing, cannot convert from 'const char [6]' to 'char [6]'
is occuring on assignment, not initialization nor the sendto
call.
Can someone with a Microsoft compiler check compile the above program and confirm the error message?
Write the assignment like this:
const char *SendBuf = "Hello";
You don't have to do anything about the function call. (A const char*
parameter will take a char*
variable as input.)
Try
char SendBuf[6] = { "Hello" };
Note the braces, which tell the compiler you're initializing an aggregate (in this case an array).
And then, instead of
SendBuf = "Hello";
which is obviously your real code, use
strcpy(SendBuf, "Hello");
or
memcpy(SendBuf, "Hello", 6);
Is there a reason why you can't pass your string literal into the method? sendTo(...,"Hello",...);
If yes then why not simple declare const char* SendBuf = "Hello";
instead of using the char array as one alternative.
Or perhaps better yet start exploring STL and use std::string SendBuf("Hello");
and pass SendBuf.c_str()
into the method.
There is always more than one way to skin a cat just pick the knife that is most comfortable for you.
精彩评论