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?
Enough is enough, std::distance(str, ptr)
or simply ptr - str
.
You can simply print this value with printf or cout with% c to get the character it points to.
printf("%c",*p);
If you want to know the position, then
printf("%td\n",ptr-str);
Just do
printf("\ndistance[%d]",ptr-str);
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.