On Aug 8, 8:49 am, Spiros Bousbouras <spi...@gmail.comwrote:
On Aug 8, 12:07 pm, Robert Gamble <rgambl...@gmail.comwrote:
On Aug 8, 7:42 am, Spiros Bousbouras <spi...@gmail.comwrote:
#include <stdlib.h>
int main(void) {
char **p1 ;
const char **p2 ;
p1 = malloc(5 * sizeof(char *)) ;
if (p1 == 0) return EXIT_FAILURE ;
p2 = p1 + 1 ;
p2 - p1 ;
return 0 ;
}
When I try to compile the above on gcc 4.1.2 I get
t.c: 10: error: invalid operands to binary -
Is it a compiler bug ?
No, it's almost never a compiler bug.
Pointer subtraction occurs between compatible pointers, p1 and p2 are
incompatible types and cannot participate in pointer subtraction. You
should have received a warning on line 9 as well as you need a cast to
make the assignment work.
I don't believe they are incompatible but rather p2 is
a qualified (with const) version of the type of p1.
You are confused, p2 is not const qualified, it is a "pointer to
pointer to const char", which is a completely distinct and
incompatible type from "pointer to pointer to char". If the pointers
were defined as:
char ** p1;
char ** const p2;
Then you would be correct as p2 would now be a "const pointer to
pointer to char" (the const qualifier being applied to the pointer
itself) thus being a "qualified version of a compatible type".
Check out questions 11.9 and 11.10 on the FAQ <http://www.c-faq.com/>
for more details.
Robert Gamble