3

I've been playing with pointers to better understand them and I came across something I think I should be able to do, but can't sort out how. The code below works fine - I can output "a", "dog", "socks", and "pants" - but what if I wanted to just output the 'o' from "socks"? How would I do that?

char *mars[4] = { "a", "dog", "sock", "pants" };

for ( int counter = 0; counter < 4; counter++ )
{
  cout << mars[ counter ];
}

Please forgive me if the question is answered somewhere - there are 30+ pages of C++ pointer related question, and I spent about 90 minutes looking through them, as well as reading various (very informative) articles, before deciding to ask.

Azoreo
  • 236
  • 1
  • 3
  • 14

5 Answers5

7

mars[i][j] will print the j'th character of the i'th string.

So mars[2][1] is 'o'.

Alex Budovski
  • 17,947
  • 6
  • 53
  • 58
  • Ugh...that was ridiculously simple. I was thinking it would have just produced a one dimensional array. – Azoreo Apr 29 '10 at 06:34
2

As has been pointed out before, strings are arrays. In fact, this concept is carried on the the std::string-class (which, by the way, is the preferred way of representing strings in C++), which implements all the requirements of an STL-Sequence. Furthermore it implements the array-subscript operator. That means the expression:

mars[i][j]

would also work if mars was declared as

std::vector< std::string > mars;

which is much more the C++ way of handling this. I realize you are doing this to learn about pointers, but I just thought I'd add this for your information. Also, when learning about pointers in C++, you should also learn about iterators, as they are generalizations of pointers.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
1
cout << mars[2][1] ;

mars is an array of char * so to get the individual char you have to index into the array of char

John Weldon
  • 39,849
  • 11
  • 94
  • 127
0

mars[counter] is of type char *, pointing to a zero-terminated string of characters. So you could:

for ( int counter = 0; counter < 4; counter++ ) 
{ 
  char * str = mars[ counter ]; 
  size_t len = strlen(str);

  if (len >= 2)
    cout << str[1]; 
} 
peterchen
  • 40,917
  • 20
  • 104
  • 186
0

Since others have suggested easy way, please also find one round-about way of doing it ;)

char *myChar = &mars[ 1 ][0];
int nPosOfCharToLocate = 1;
myChar = myChar + nPosOfCharToLocate;
cout <<*myChar<<endl;
Akaanthan Ccoder
  • 2,159
  • 5
  • 21
  • 37