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
c ++ c arrays pointers


source to share


4 answers


Enough is enough, std::distance(str, ptr)

or simply ptr - str

.



+11


source to share


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);

      

+2


source to share


Just do

   printf("\ndistance[%d]",ptr-str); 

      

0


source to share


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







All Articles
Loading...
X
Show
Funny
Dev
Pics