Non-Portable pointer assignment?

D'Arcy J.M. Cain darcy at druid.uucp
Mon Jun 3 13:06:41 AEST 1991


In article <mccX31w164w at cybrspc> Roy M. Silvernail writes:
>I use Turbo C, and sometimes get the warning "Non-portable pointer
>assignment" when I do something like this:
>foo(char *p) {
>    char *q;
>
>    q = strchr(p,'x');  /* this line gets complaints */
>}
That's because the compiler sees you trying to assign an int to a pointer
to character.  To my mind it is being too polite.  It should say "Assignment
of pointer from integer lacks a cast" as well as telling you that strchr
is used without being declared.  Note that with Turbo C, like many other
ANSI compilers, will let you turn on lots of warnings and if you had done
so it would have caught this. (*)

>TFM says strchr() returns pointer to char, and the pointer I'm assigning
>to is a pointer to char, so I'm in the dark.  On my platform, the code
>works, but I try to write portably.
Unfortunately the compiler hasn't read TFM.  It doesn't know what strchr
returns.  It also doesn't know what arguments it expects so it can't
check them for you (they're fine here.)  To protect yourself you should
include the line:

extern char *strchr(const char *str, int ch);

or even better:

#include <string.h>

BTW, TFTM (The fine Turbo manual) shows you which header file(s) you
should include if you call a function.  If you include the ones it
indicates you will save yourself lots of grief one day.

>So, what's the proper (perhaps the ANSI) way to handle such an
>assignment?  If Turbo is right, this snip of code will fail on other
>machines or other compilers.
It might fail With Turbo with a different memory model.

(*) My favorite CFLAGS with GNU C:
    CFLAGS = -O -Wall -ansi -pedantic
and I still expect my programs to compile with no errors or warnings.

-- 
D'Arcy J.M. Cain (darcy at druid)     |
D'Arcy Cain Consulting             |   There's no government
Toronto, Ontario, Canada           |   like no government!
+1 416 424 2871                    |



More information about the Comp.lang.c mailing list