Re: calculating length of an substring



"brasilino@xxxxxxxxx" <brasilino@xxxxxxxxx> writes:

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;

You wanted
len = (int)(s - e);
.. The way you have it, only s will be cast to an int; and you can't
subtract a pointer from an int!

The cast is completely superfluous, though; I'd recommend removing
it. If you like, you can first check that it will actually _fit_ into
an int (the type of the difference of pointers is ptrdiff_t, defined
in <stddef.h>. Or better yet, use a ptrdiff_t to store the result (if
that suits your needs otherwise).

A size_t actually makes the most sense for representing a string
length, though, at least to me.

--
Micah J. Cowan
Programmer, musician, typesetting enthusiast, gamer...
http://micah.cowan.name/
.



Relevant Pages

  • swap using pointers
    ... int swap; ... incompatible pointer type ...
    (comp.lang.c)
  • 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)