Function returning a pointer to an int array

若如初见. 提交于 2019-12-01 22:12:44
Grijesh Chauhan

Read: What does sizeof(&array) return? to understand diffrence between array name and address of array.

Q1 I want to know the difference between:  

In your code:

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

you are returning address of first element. Actually type of a is int[3] that decays into int*. Important is
You stores address into int* p and can assess elements of array as p[i].

Whereas if your function would be int int (*func())[3] then you return &a, and assign to int(*p)[3] and can access (*p)[i].
Note: type of &a is int(*)[3].

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

like:

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

And main():

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

You can check second version of code working id Ideone

Q1 I want to know the difference between:  

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 as p[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.

int(*)[10] is a pointer to an array of 10 ints. int* is a pointer to int. These are different types.

However, an array decays to a pointer to its first element, so you can do:

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

But not:

q = p;
p = q;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!