tags:

views:

91

answers:

5

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.

+7  A: 

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

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

Alex
Ugh...that was ridiculously simple. I was thinking it would have just produced a one dimensional array.
Matt
+1  A: 
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
A: 

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
This answer is above my head, unfortunately :9
Matt
+1  A: 

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.

Space_C0wb0y
A: 

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