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.
int(*)[10]
is a pointer to an array of 10int
s.int*
is a pointer toint
. These are different types.However, an array decays to a pointer to its first element, so you can do:
But not:
Read: What does sizeof(&array) return? to understand diffrence between
array name
andaddress of array
.In your code:
you are returning address of first element. Actually type of
a
isint[3]
that decays intoint*
. Important isYou stores address into
int* p
and can assess elements of array asp[i]
.Whereas if your function would be int
int (*func())[3]
then you return&a
, and assign toint(*p)[3]
and can access(*p)[i]
.Note: type of
&a
isint(*)[3]
.like:
And main():
You can check second version of code working id Ideone
As you are interested to know diffrence between two so now compare two different declarations of
p
in two versions of code:1) :
int* p;
and we access array elements asp[i]
that is equals to*(p + i)
.2) :
int (*p)[i]
and we access array elements as(*p)[i]
that is equals to*((*p) + i)
or just =*(*p + i)
. ( I added()
around*p
to access array element because precedence of[]
operator is higher then*
So simple*p[i]
means defense to the array elements).Edit:
An addition information other then return type:
In both kind of functions we returns address that is of a static variable (array), and a static object life is till program not terminates. So access the array outsize
func()
is not a problem.Consider if you returns address of simple array (or variable) that is not static (and dynamically allocated) then it introduce as Undefined behavior in your code that can crash.