Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ukma!rutgers!att!cbnewsh!rkl From: rkl@cbnewsh.ATT.COM (kevin.laux) Newsgroups: comp.lang.c Subject: Re: When is a cast not a cast? Message-ID: <364@cbnewsh.ATT.COM> Date: 2 May 89 16:10:38 GMT References: <2747@buengc.BU.EDU> Organization: AT&T Bell Laboratories Lines: 53 In article <2747@buengc.BU.EDU>, bph@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