c - Pass unsigned char pointer to atoi without cast -
on embedded device, have passed unsigned char
pointer atoi
without cast.
unsigned char c[10]="12"; atoi(c);
question: defined?
i saw somewhere ok string functions, not sure atoi
.
edit: btw. concerns have been expressed on 1 of answer below might not ok string functions such strcpy - if got right (?) author meant can in practice can ok.
also here, ok following assignment unsigned char
pointer ok too? because used tool complaining "type mismatch (assignment) (ptrs signed/unsigned)"
unsigned char *ptr = strtok(unscharbuff,"-"); // assignment ok unsigned char?
no, it's not defined. it's constraint violation, requiring compile-time diagnostic. in practice it's very work expect, it's not guaranteed so, , imho it's poor style.
the atoi
function declared in <stdlib.h>
as:
int atoi(const char *nptr);
you're passing unsigned char*
argument function expects char*
argument. 2 types not compatible, , there no implicit conversion 1 other. conforming compiler may issue warning (that counts diagnostic) , proceed generate executable, behavior of executable undefined.
as of c99, call function no visible declaration constraint violation, can't away omitting #include <stdlib.h>
.
c still permit calls functions visible declaration declaration not prototype (i.e., doesn't define number of type(s) of parameters). so, rather usual #include <stdlib.h>
, add own declaration:
int atoi();
which permit calling unsigned char*
argument.
this "work", , might possible construct argument standard behavior defined. char
, unsigned char
values of '1'
, '2'
guaranteed have same representation
but it's far easier add cast prove it's not necessary -- or, better yet, define c
array of char
rather array of unsigned char
, since it's intended hold string.
unsigned char *ptr = strtok(unscharbuff,"-");
this constraint violation. there no implicit conversion unsigned char*
char*
first argument in strtok
call, , there no implicit conversion char*
unsigned char*
initialization of ptr
.
Comments
Post a Comment