Re: calculating length of an substring



Hi All!

I'd like to thanks to everybody who answer. I have forgotten
the cast precedence from any math operation!!!

thanks a lot!

Lucas Brasilino

brasil...@xxxxxxxxx wrote:
Hi Folks:

I'm trying to calculating a substring length directly from pointer
address, like this:

char *e = NULL, *s = NULL;
int len = 0;

s = strchr (url,'.');
e = strrchr (url,'?');
len = (int) s - e;

^^^^^
Not only is a cast unneeded, it introduces an error into your program.
You are trying to subtract a pointer from an int.



Since 's' and 'e' are pointers, I think that's can be make a math
over it, like 's++'.

But your subtraction is a pointer from an int, not a pointer from a
pointer. If you _must_ use an unneccesary cast, use
len = (int)(s - e);
but that means exactly the same thing as the cast-less
len = s - e;



Using gcc 4.1.2 (on glibc 2.6 and Linux 2.6.23) it points the
following error:

"error: invalid operands to binary -"

And that is obviously true.

.



Relevant Pages

  • Re: Reading a string of unknown size
    ... "Don't cast return value of malloc() in C. ... It is entirely possible for an int to be returned by a ... function using a different method than that used to return a pointer. ...
    (comp.lang.c)
  • Re: Is this code valid
    ... | the program, or a null pointer, or a pointer to non-modifiable ... is promoted to `unsigned int'. ... implementations), the cast is therefore necessary. ...
    (comp.lang.c)
  • Re: A little help please
    ... >>You don't need the cast. ... void* to another pointer type. ... if arr points to first element of int array then I thought by ...
    (alt.comp.lang.learn.c-cpp)
  • Re: How do you cast an integer to a pointer?
    ... One usage I've made of casting into an int (in C++, ... cast to and then back from an int. ... puoi assegnare il valore di un pointer ad una variabile ... Su un processore a 16bit, con 16bit di indirizzamento, un pointer e' un ...
    (comp.lang.fortran)
  • Re: const int * assignment
    ... As the new pointer type does not point to ... I am confused about this cast type for const ... This can be a dangerous thing to do if the int ...
    (comp.lang.c)