读书人

数组与指针的关系?求

发布时间: 2012-09-29 10:30:01 作者: rapoo

数组与指针的关系?求高手指点
我写了一段简单的代码,测试引用方式传递指针变量,同时测试了关于数组与指针的关系,代码中 vec , &vec , &vec[0]的值相同?为什么 int* result = &vec 运行失败?具体代码如下

C/C++ code
#include <iostream>#include <windows.h>using namespace std;void firstBegin(int*& p, int value) {    while(*p <= value) {        p++;    }}void main() {    int vec[] = {1,12,32,44,33,6,85,4,100};    cout<<vec<<endl;    cout<<&vec<<endl;    cout<<&vec[0]<<endl;    //int* result = vec; //succeed    [color=#FF0000]int* result = &vec;//error ? why?[/color]    //int* result = &vec[0]; //succeed    firstBegin(result,60);    cout<<"Begin at "<<*result<<endl;    system("pause");}


[解决办法]
If the type of an expression or subexpression is ``array of T,'' for some type T, then the value of the expression is a pointer to the first object in the array, and the type of the expression is altered to ``pointer to T.'' This conversion does not take place if the expression is in the operand of the unary & operator, or of ++, --, sizeof, or as the left operand of an assignment operator or the . operator. Similarly, an expression of type ``function returning T,'' except when used as the operand of the & operator, is converted to ``pointer to function returning T.''
[解决办法]
数组名在3种情况下不会转换为指针:其中一种就是 &array
[解决办法]
探讨
引用:
你的vec已经是一个指针了 为啥还要取地址??
int* result = vec;

我是看到 vec,&vec[0],&vec三者的值是相同的,就想通过下面的语句测试一下是不是真的完全等价的

读书人网 >C++

热点推荐