简体   繁体   中英

C : Accessing contiguous array elements using a pointer returned by a function

In the following program, I get the output 1 0 0 2130567168 11 2686668 7 2686916

whereas according to me the output must be 1 2 3 4 5 6 7 8

because the array elements are stored in contiguous memory locations and I am accessing those elements in a contiguous fashion.

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

int *fun3();

int main(){
    int j, k;
    int *q = fun3();
    for(j = 0; j < 8; j++){
        printf("%d\t", *(q+j));
    }
}

int *fun3(){
    int a[] = {1,2,3,4,5,6,7,8};
    return a;
}

Please suggest any problems in my code or my reasoning.Why am I getting this unusual behaviour?

The array a has automatic storage duration, which ends when the function fun3() returns. This means it's not legal to access it after this point - doing so has undefined behaviour, which means anything can happen.

int a[]的生命周期仅限于fun3 ,因此您无法返回它并期望它保持有效。

int a[] of function fun3 is local scope. scope of a is no longer valid if you get out of this function. It is one way it is because since an auto variable is storage class for example is to change the static .

int *fun3(){
    static int a[] = {1,2,3,4,5,6,7,8};
    return a;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM