When is a cast not a cast?
kevin.laux
rkl at cbnewsh.ATT.COM
Wed May 3 02:10:38 AEST 1989
In article <2747 at buengc.BU.EDU>, bph at buengc.BU.EDU (Blair P. Houghton) writes:
| Here's one that popped up last night/this morning (keep that Sanka
| away from me! %-S )
|
| I wanted to be a 'good little programmer' and make all the types
| match up, so I was using casts wherever a promotion might be
| non-obvious. In particular, I fell for: (the line numbers are shown
| only for reference)
|
| 1 main()
| 2 {
| 3 char *c;
| 4 char *p;
| 5 int i;
| 6 ...
| 7 c = "somestring"; /* Nothing fancy, null-terminated. */
| 8 i = 4; /* For example. */
| 9 ...
| 10 p = (c + (char *) i); /* More trouble than it's worth... */
| 11 ...
| 12 }
|
| wherupon both the lint(1) and cc(1) in my Ultrix 2.2 piped-up with
| warnings that the 'operands of + have incompatible types' on line 10...
|
| Now, who is having the more serious problem with (reduntantly?) casting
| i to be a char * before this addition: me, or the programmming tools
| under Ultrix version 2.2?
[ stuff deleted ]
But you want p to point into the string by an offset i.
Line 10 should simply be
p = c + i;
so that the value of pointer c is incremented by the value of integer i
times the sizeof a char.
You don't want to add two *pointers* together and place the result in
p. Think about the result from subtacting two pointers:
char c [8];
char *p;
int i;
p = &c [7];
i = p - c;
The result of p - c is 8, an integer.
--rkl
More information about the Comp.lang.c
mailing list