Reputation: 19
#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.
Upvotes: 0
Views: 1329
Reputation: 438
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++?
Upvotes: 1
Reputation: 13924
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'
"
Upvotes: 1
Reputation: 132984
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;
Upvotes: 4