0
#include<iostream> using namespace std; main() { char *p[4] = {"arp","naya","ajin","shub"}; cout<<*p[2]; // How is this printing 'a' // how can i print the elements of each of the 4 strings // except the first character 

}

Visit http://cpp.sh/7fjbo I'm having a lot of problems in understanding handling of pointers with strings. If you can help with that, please post some additional links. Underastanding the use of arrays with pointers is my primary concern.

2
  • Fill it with different data so you can know which char it is printing.. Commented Aug 2, 2016 at 14:29
  • If you do this only to practise pointers then it's ok, BUT I would like to point out that ISO C++ forbids conversion between string constant (and "ajin" is exactly that) and char* . You should use std::string if it's not only for learning purposes. Commented Aug 2, 2016 at 14:30

3 Answers 3

4

p[2] is a pointer to the first element of "ajin". When you dereference it, you get a. If you want to print all of it, use the pointer itself

cout << p[2]; 

If you want to skip the first characters, pass a pointer to the second character to cout, i.e.

cout << p[2] + 1; 
Sign up to request clarification or add additional context in comments.

3 Comments

You could also use cout << p[2][1] .
@Lehu: That would print only the second character. p[2][1] is equivalent to *(p[2] + 1), not p[2] + 1
Sure, but he wanted to access individual characters :) . Ah! In the comments he wrote about skipping first character!
1

Here, p is basically array of string pointers with array length 4.

*p[2] is same as p[2][0]

p[2] is same as "start from index 0 and print till the compiler finds '\0'"

p[2] + i is same as "start from index i and print till the compiler finds '\0'"

1 Comment

If it's C++ (and it is) I would write that p is array of char**. If I see "string pointer" mentioned then for me it's string* which is not the case here.
1

Some more information in addition to Armen's answer to give you a better understanding.

C++ is not exactly C; it is a strongly typed language. In C, you use char * to denote a null-terminated string. But actually, it means a pointer to the char type. C++, being strongly typed, is invoking

std::ostream& std::ostream::operator<<(std::ostream& cout, char); 

with

cout << *p[2]; 

since the second operand is of type char.

In C++, you may want to use std::string instead of char* because the former is safer and has an easier interface. For details, you can refer to Why do you prefer char* instead of string, in C++?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.