Re: calculating length of an substring



brasilino@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: Memory Structure Pointer Problems
    ... typedef struct sta { ... char* name; ... int num_cmpnds; ... A pointer to a struct cmp is almost ...
    (comp.lang.c)
  • Re: C# - getting binary data from .lib
    ... Use Marshal.AllocHGlobal to allocate the memory and pass this IntPtr to the ... int retCode = create(id, scale, ptrImage); ... You now control the pointer returned. ...
    (microsoft.public.dotnet.framework.interop)
  • Re: Another spinoza challenge
    ... You should test against the int type's limits: ... typedef struct complex ... a pointer to an integer ... A macro is preferable because it is replaced by inline code, ...
    (comp.lang.c)
  • Re: C# - getting binary data from .lib
    ... int create(int id, int scale, unsigned char *image); ... unsigned char* ptrImage = NULL; ... // Read through entire pointer byte by byte and put into managed array ...
    (microsoft.public.dotnet.framework.interop)
  • Re: C# - getting binary data from .lib
    ... then there is a problem with the ptrImage ... int retCode = create(id, scale, ptrImage); ... You now control the pointer returned. ...
    (microsoft.public.dotnet.framework.interop)