strncpy - warning

15 Jun 2011

Hello,

#include "mbed.h"

typedef struct G {    
    unsigned char rec[20];
} g;

g rdata;

int main() {
    unsigned char buf[12];

    strncpy( buf, rdata.rec, 11 );
}

Above coding i received this warning: "Argument of type "unsigned char *" is incompatible with parameter of type "char *" (E167)" and "Argument of type "unsigned char *" is incompatible with parameter of type "const char *" (E167) "

This coding work fine in Keil compiler but mbed compiler shown warning. If i change the data type to char the warning will disappear. I have to use unsigned char rather than using char. How can i solve it?

Thank you,.

15 Jun 2011

What is to solve. you have the solution. Some compilers take (or can be configured to take) a char as unsigned by default. When you get tired of typing 'unsigned' you could do something like:

#define char unsigned char //very ugly
or
typedef unsigned char uchar; //better
15 Jun 2011

You can just force a cast to get rid of the error and in this particular case there is no risk since the types are the same size.

#include "mbed.h"

typedef struct G {    
    unsigned char rec[20];
} g;

g rdata;

int main() {
    unsigned char buf[12];

    strncpy( (char*)buf, (char*)rdata.rec, 11 );
}

You might want to consider just using a memcpy for such a small array. It will copy bytes past the NULL terminator but those are valid memory locations in your example and the copy loop won't have to check for the terminator on each byte and might be able to do the copy a word at a time instead of a byte at a time. memcpy() takes void* pointers so the compiler will implicitly cast your unsigned char* pointers for you with no errors/warnings.

#include "mbed.h"

typedef struct G {    
    unsigned char rec[20];
} g;

g rdata;

int main() {
    unsigned char buf[12];

    memcpy(buf, rdata.rec, sizeof(buf)-1 );
}
17 Jun 2011

Hello Ad van der Weiden, Hello Adam Green,

Thanks for you all reply. The explanation is very good. Did solve the warnings. Thanks a lot.

Bst Rrgds, Wen.