开发者

Doubts in the strcpy function used

I am using two buffers which are of unsigned char and when I used the function strcpy, there is a compilation error which says "invalid conversion of unsigned char * to char *". Can anyone please tell me what difference does an unsigned buffer vs. signed buffer makes to the output? This is the program which I had tried.

        main()
        {
                unsigned char buff[20] = "Michael";
                unsigned char dst[20] = "Jackson";
                strcpy(buff,dst);
                printf("The string is %s\n",buff);

        }

Now when i typecast the parametrs passed in strcpy to (char *),This programe works fine as shown below

        main()
       开发者_Go百科 {
                unsigned char buff[20] = "Michael";
                unsigned char dst[20] = "Jackson";
                strcpy((char *)buff,(char *)dst);
                printf("The string is %s\n",buff);

        }

2nd Question: Does typecasting to char* in the string function create any issues?

Please do let me know if you need any more inputs.


You can just change:

unsigned char buff[20] = "Michael";
unsigned char dst[20] = "Jackson";

to

char buff[20] = "Michael";
char dst[20] = "Jackson";

To think of it logically, A string cannot be signed or unsigned, it is not a numeric value to be treated that way, it is just an char array and you should declare and use it so.

Why do you get the error?
strcpy has the prototype:

char *strcpy(char *restrict s1, const char *restrict s2);

And what you are passing to it is, unsigned char*, when a function is called parameter type checking takes place and the compiler finds that you are not calling the function with proper type parameters and hence it complains about it, When you apply a cast the function arguments match and hence compilation passes.

Does typecasting to char in the string function create any issues?*
No, in this case it doesn't.
Though it makes more sense to change your usage of unsigned char for the reasons mentioned above in the answer.

Suggestion:
Strcpy is not safe, so you are much better off using strncpy, it allows you to explicitly specify how many characters to copy, rather than rely on null terminator of the source string, Also this helps avoiding buffer overflow since you explicitly specify a length.


The way you are using it should be fine.

But you shouldn't use unsigned char arrays with string handling functions. In C strings are char arrays, not unsigned char arrays. Since passing to strcpy discards the unsigned qualifier, the compiler warns.

As a general rule, don't make things unsigned when you don't have to.


strcpy wants char *'s, plain and simple. Cast your buffers to char *'s and you'll be fine. Then there's the whole safety problem with using strcpy in the first place...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜