4

I am learning C++ from Primer 5th edition and I am at Returning a Pointer to an Array. The declaration of this function is:

 int (*func(int i))[10]; 

and it's expected to return a pointer to an array.

I wrote code that does this:

#include <iostream>
#include <string>
using namespace std;

int *func(){
  static int a[]={1,2,3};
  return a;
}
int main (){
  int *p=func();
  for(int i=0;i!=3;++i){
    cout<<*(p+i);
  }
}

And it is working. But I want to know the difference between what I made here and

  int (*func(int i))[10]; 

How I can make this function call work, because in the book, there isn't any concrete example.

4

2 回答 2

3

阅读:sizeof(&array) 返回什么? 了解 和 之间的array name差异address of array

Q1我想知道两者之间的区别:  

在您的代码中:

  int *func(){
    static int a[]={1,2,3};
    return a;
  }

您正在返回第一个元素的地址。实际上类型aint[3]衰减成int*. 重要的是
您将地址存储到int* p并且可以将数组的元素评估为p[i].

而如果你的函数是 intint (*func())[3]那么你返回&a,分配给int(*p)[3]并且可以访问(*p)[i]
注:类型&aint(*)[3].

Q2我怎样才能使这个函数调用工作,因为在书中,没有任何具体的例子。

喜欢:

int (*func())[3]{
    static int a[]={1,2,3};
    return &a;
}

和主要():

int main(){ 
 int i=0;    
 int(*p)[3] = func();
 for(i=0; i<3; i++)
   printf(" %d\n", (*p)[i]);
 return 0;
}

您可以检查代码工作 id Ideone的第二个版本

Q1我想知道两者之间的区别:  

由于您有兴趣了解两者之间的差异,因此现在比较p两个版本代码中的两个不同声明:

1) : int* p;我们访问数组元素,因为p[i]它等于*(p + i)

2) : int (*p)[i]我们访问数组元素,因为(*p)[i]它等于*((*p) + i)或只是 = *(*p + i)。(我添加()*p访问数组元素,因为[]运算符的优先级高于*所以简单*p[i]意味着对数组元素的防御)。

编辑:

除了返回类型之外的附加信息:

在这两种函数中,我们都返回静态变量(数组)的地址,而静态对象的生命周期是直到程序不终止。所以访问超大的数组func()不是问题。

考虑如果您返回非静态(并且动态分配)的简单数组(或变量)的地址,那么它会在您的代码中引入可能崩溃的未定义行为。

于 2013-07-26T13:52:40.107 回答
2

int(*)[10]int是一个指向 10 s数组的指针。int*是指向 的指针int。这些是不同的类型。

但是,数组衰减为指向其第一个元素的指针,因此您可以这样做:

int a[10];
int(*p)[10] = &a;
int* q = a; // decay of int[10] to int*

但不是:

q = p;
p = q;
于 2013-07-26T13:50:09.283 回答