简体   繁体   English

如何访问指针数组中字符串的各个元素?

[英]How can i access individual elements of a string in an array of pointers?

#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. 访问http://cpp.sh/7fjbo在理解带有字符串的指针的处理时遇到很多问题。 If you can help with that, please post some additional links. 如果您可以提供帮助,请发布一些其他链接。 Underastanding the use of arrays with pointers is my primary concern. 理解将数组与指针一起使用是我的主要关注点。

p[2] is a pointer to the first element of "ajin" . p [2]是指向"ajin"的第一个元素的指针。 When you dereference it, you get a . 取消引用时,会出现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, ie 如果要跳过第一个字符,则将指向第二个字符的指针传递给cout,即

cout << p[2] + 1;

Here, p is basically array of string pointers with array length 4. 在这里, p基本上是长度为4的字符串指针数组。

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

p[2] is same as "start from index 0 and print till the compiler finds '\\0' " p[2]与“从索引0开始并打印直到编译器找到'\\0'

p[2] + i is same as "start from index i and print till the compiler finds '\\0' " p[2] + i与“从索引i开始并打印直到编译器找到'\\0'

Some more information in addition to Armen's answer to give you a better understanding. 除了Armen的答案以外,还有一些其他信息可以使您更好地理解。

C++ is not exactly C; C ++ 并不是 完全 C。 it is a strongly typed language. 这是一种强类型的语言。 In C, you use char * to denote a null-terminated string. 在C语言中,您可以使用char *来表示一个以空值结尾的字符串。 But actually, it means a pointer to the char type . 但是实际上,这意味着指向char类型的指针 C++, being strongly typed, is invoking 强类型的C ++正在调用

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

with

cout << *p[2];

since the second operand is of type char . 因为第二个操作数是char类型。

In C++, you may want to use std::string instead of char* because the former is safer and has an easier interface. 在C ++中,您可能要使用std::string代替char*因为前者更安全并且界面更简单。 For details, you can refer to Why do you prefer char* instead of string, in C++? 有关详细信息,请参阅在C ++中为什么更喜欢char *而不是string?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM