【发布时间】:2013-05-26 14:56:08
【问题描述】:
好的,根据我对指针数组的理解:
一个数组被认为是一个常量指针的等价物,因为它指向它的每个索引元素。指向数组的指针也等同于第一个索引的地址。
好吧 - 因为这是有效的:
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
在这种情况下 char 指针真的很特别吗?这给我带来了另一个关于流式传输函数的问题,您可以通过增加点并指定大小来指定可以写入/读取的字节数(例如 in ofstream::write(char pointer, size);) 此外,将结构类型转换为字符指针可以将其转换为字节数组吗?
任何澄清将不胜感激,谢谢。
【问题讨论】:
-
指针不是数组,反之亦然。它们是不同的。
-
参见c-faq.com/aryptr/aryptrequiv.html,其中详细阐述了@chris 的观点。
标签: c++ arrays pointers stream byte