c pointers (ptrdiff_t)

A

andy_dufresne

hi,
i'd a question abt taking the difference between two pointers.
for eg: if you have 2 char pointers pointing to members of an array,
you advance one till you encounter a space then take the difference
between
the two, will give the correct length of the string irrespective of
whether char is represented by 2 bytes (like in unicode)?? i believe it
would give the correct length, because the compiler is responsible for
scaling the difference when one advances a pointer to point to the next
element like ptr++, or is it that pointer difference (subtraction
between two
pointers to members of the same array) is not pointer arithmetic and we
need
to scale it??

eg problem:
Orig string - char *s;
Ptrs, char *start = s, *end = s;
int length;
while(!isspace(*end))
end++;
length = end - start;

is this mentioned somewhere in the c std?? if so could someone pt me in
the right direction.

Thanks.
 
M

Mark McIntyre

hi,
i'd a question abt taking the difference between two pointers.
for eg: if you have 2 char pointers pointing to members of an array,
you advance one till you encounter a space then take the difference
between
the two, will give the correct length of the string

the difference between the two pointers to array elements will give
you the difference between the array indices. So yes.
irrespective of
whether char is represented by 2 bytes (like in unicode)??

char is /always/ one byte in C - this is by definition. A character,
on the other hand, may require more than one byte. Such objects cannot
fit into chars.
length = end - start;

length should be ptrdiff_t, to be safe. This type is designed to hold
the difference between two pointers.
is this mentioned somewhere in the c std?? if so could someone pt me in
the right direction.

6.5.6 para 9.
When two pointers are subtracted,....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

ptrdiff_t (pointer arithmetic) 1
Help with pointers 1
ptrdiff_t 13
Pointers 16
Copy string from 2D array to a 1D array in C 1
Function Pointers 0
Arrays & Pointers 2
pointers as parameters 6

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top