好吧,根据我对指针数组的理解:
数组被认为等同于常量指针,因为它指向每个索引元素。另外,指向数组的指针相当于第一个索引的地址。
好吧 - 因为这是有效的:
int test[] = {1, 2, 3}
int * point = test;
cout << test + 2; //gives the address of the 3rd element test[2]
我想知道,为什么会有不同的行为?
char arr[] = "testing pointer arrays";
char * pointer = arr;
cout << pointer + 3 << endl; //would output the actual string at pos arr[3]
同样:
char * test = "zomg";
cout << test + 2; //outputs mg
在这种情况下,字符指针真的很特殊吗?这让我想到了另一个问题,关于如何在流式处理函数中,您可以通过增加点并指定大小来指定可以写入/读取的字节数(例如在 ofstream::write(char point, size); 中)此外,将结构体类型转换为字符指针可以将其转换为字节数组吗?
如有任何澄清,我们将不胜感激,谢谢。
最佳答案
这个
char arr[] = "hello";
相当于
char arr[] = {'h', 'e', 'l', 'l', 'o', '\0'};
唯一的区别是字符串文字的含义,例如 "hello"
,而不是 char
数组的方式治疗比照。其他内置类型的那些。
接下来,当您传递char*
时至std::cout
std::cout << pointer + 3 << endl;
您会受益于 ostream& operator<<
有一个特殊的重载。对于 char*
,它将指针视为以 null 结尾的字符串的第一个元素。
关于c++ - 指针数组困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760440/