1

I'm new to C so please be patient. I created a function initialization that I want to return the array that I create and modify within initialization. Now I know that I cannot return an array in C but what I can do is return a pointer to the array by specifying the arrays name in the return statement. For some reason, when I do this I receive this warning. Now I know that the the lifetime of arr inside of initialization extends only to the end of initialization then the memory is deallocated but I'm unsure how to work around this. If someone could explain what is going on it would be much appreciated.

returning ‘int (*)[(sizetype)(n)]’ from a function with incompatible return type ‘int *’

warning: function returns address of local variable [-Wreturn-local-addr]

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

int *initialization(int n);
int main()
{
    int dim = 2;
    *p = initialization(dim);

    return 0;
}

int *initialization(int n)
{
    int arr[n][n];
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            arr[i][j] = 1;
        }
    }
    return arr;
}
anastaciu
  • 23,467
  • 7
  • 28
  • 53

1 Answers1

0

Local automatic variables stop to exist when the function returns.

You can return the reference to the local object, but you cannot dereference it as the memory location it references becomes invalid after the function return.

0___________
  • 60,014
  • 4
  • 34
  • 74