Where am I in my array?
this is auto-generated C code so please ignore my scrolling method though the char pointer
I am using a char pointer to store a string:
char str[] = "Hello!";
char *ptr = str;
And I use pointer arithmetic to loop through it:
++ptr;
++ptr;
...
...
--ptr;
At some point, I would like to know what kind of pointer it is pointing to (eg 1 for "e" in "Hello"). How to do it?
+3
source to share
4 answers
To answer your question, the simplest way is to use std :: distance. This will return the number of elements between the given iterators. In your case, std :: distance (str, ptr) returns the number of elements between str and ptr. Say str points to the beginning and ptr is somewhere in 'o', then the value returned by this API is 4.
0
source to share