3

this is automatically generated C code, so please don't mind my method of scrolling though a char pointer

I'm using a char pointer to store a string:

char str[] = "Hello!";
char *ptr = str;

And I use pointer arithmetic to scroll through it:

++ptr;
++ptr;
...
...
--ptr;

I'd like to know at some point to exactly what index it's pointing (eg. 1 for 'e' in "Hello"). How do I do this?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Mark
  • 1,258
  • 13
  • 25

4 Answers4

11

Appropriately enough, std::distance(str, ptr) or just ptr - str.

Don Reba
  • 13,814
  • 3
  • 48
  • 61
2

You can Simply print that corresponding value with printf or cout with %c to get the character where that is pointing.

printf("%c",*p);

If you want to know the position then

printf("%td\n",ptr-str);
Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31
  • 2
    the correct format is [`%td`](http://stackoverflow.com/questions/7954439/c-which-character-should-be-used-for-ptrdiff-t-in-printf), not `%d` – phuclv Dec 09 '14 at 11:07
  • @LưuVĩnhPhúc Thank you I done that in editing. But normally use the %d it is working. – Karthikeyan.R.S Dec 09 '14 at 12:43
  • no, stricly speaking, it's undefined behavior, esp. in systems with pointers larger than 32 bits like 64-bit architectures – phuclv Dec 09 '14 at 12:45
0

Just do

   printf("\ndistance[%d]",ptr-str); 
Saravanan
  • 1,270
  • 1
  • 8
  • 15
  • 1
    the result of the subtraction between 2 pointers isn't an int, so using `%d` invoke undefined behavior – phuclv Dec 09 '14 at 11:07
0

To answer your question, simplest way is use std::distance. This will return the number of elements between the given iterators. In your case, std::distance(str, ptr) return the number of elements between str and ptr. Say str is pointing to start and ptr is somewhere at 'o', then the value returned by this API is 4.