-7

i have watched tutorial that explain how to return array from function

and this is similar code

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int *grn();

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

int *grn(){
    static int arrayy[10];
    srand((unsigned) time(NULL));
    for(int i=0;i<10;i++){
        arrayy[i]=rand();
    }
    return arrayy;
}

and i have some questions about it.. it is work fine and generate random values inside the array but

  • why the function grn is pointer

  • and why a variable in the main function is pointer ?

  • why the arrayy array is static?
  • and why should i make the grn function pointer?

when i try to run this code but the arrayy variable is not static i get segmentation fault

FRe34
  • 105
  • 11
  • 3
    [See here](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). What's with the flood of absolute beginner questions the last week or so? – M.M Sep 05 '16 at 21:59
  • 3
    SO is not a programming school. – Barmar Sep 05 '16 at 22:01
  • _There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs._ – Sourav Ghosh Sep 05 '16 at 22:05
  • I'd recommend looking for a better tutorial. The function is **not** returning an array (because you *can't* return an array). – EOF Sep 05 '16 at 22:05

1 Answers1

0
  1. The function isn't the pointer. The return value is int * since it returns an array of int.

  2. You need a pointer to access an array. If it's not a pointer, then you are expecting a single int variable.

  3. If it's not static, then the array will be deallocated and gone when the function reached to return. The array is neither a global variable, nor an allocated memory in heap, so it will be deallocated when the function reached to return. If you make it static, it works like a global variable (not exactly) and will not be deallocated when the function reaches to the end.

  4. Read number 1.

Lastly, you get segmented fault because the function returned a dangling pointer because the array is not static therefore deallocated when the function reached to the end.

user2821630
  • 112
  • 1
  • 1
  • 10
  • Pretty much everything is correct other than "an array of int should be a pointer". An array of int is an array of int and you need a pointer that points to integers to access any values that may be stored inside an array of integers. – Spidey Sep 05 '16 at 22:11
  • @Spidey Thanks for your correction. – user2821630 Sep 05 '16 at 22:12
  • although they put my question in hold but you answer make it easy to understand this code .. thanks man – FRe34 Sep 06 '16 at 14:04