Why is there a difference when assigning an array with static keyword and without to a pointer?

Viewed 84

The code below works correctly and gives the output 4:

int main()
{

    int *res = valout();
    printf("%d", res[0]);
}

int *valout()
{
    static int arr[] = {4, 5, 6};
    return arr;
}

The code below returns a segmentation error:

int main()
{

    int *res = valout();
    printf("%d", res[0]);
}

int *valout()
{
    int arr[] = {4, 5, 6};
    return arr;
}

Why do we get an error in case 2 and not in case 1? What role does the static keyword play here? Please elaborate on this issue.

3 Answers

It's because:

static int arr[] = {4, 5, 6};

creates a static array (obviously), defined as a variable that exists from the moment of it's creation until the program exits.

On the other hand:

int arr[] = {4, 5, 6};

creates a variable that exists only within the limited scope of the function (or block) in which it is defined. It ceases to be when the function exits.

In both cases, return arr returns the address of the first element of that array. Unfortunately, with the non-static variant, there's no correct way to use that address because the underlying object it refers to has ceased to be. Hence, it will complain about it.

The static version, remaining in existence until program exit, can be used after function exit.

Because there is a different between static variable and local variable so in the first program when you define

static int arr[] = {4, 5, 6};

this variable (arr) will be exist(define) until the fish of the program so when you call the valout() function in the main function then print the first element which exist in the static variable it is still exit (as it will not remove from the memory till the program finish But in the second program you define array as (a local variable) so it will be define between {} of valout() function only so when you call it in the main function

 int *res = valout();

program will execute this function but you want to print the first element of the arr compiler can't see it as it wil be removed from the memory once the valout() function exit

static variables have static storage duration which has program lifetime duration.

automatic variables have automatic storage duration - and exists only as long as the the scope they are defined in, in your case the function scope.

When you return the reference to the automatic variable - you return the reference to the non existent object. It is the UB.

Related