简体   繁体   English

C:使用函数返回的指针访问连续数组元素

[英]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 在以下程序中,我得到输出1 0 0 2130567168 11 2686668 7 2686916

whereas according to me the output must be 1 2 3 4 5 6 7 8 而根据我的输出必须是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. 数组a具有自动存储持续时间,该持续时间在函数fun3()返回时结束。 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. 函数fun3 int a[]是局部作用域。 scope of a is no longer valid if you get out of this function. 如果您退出此功能,则a的范围不再有效。 It is one way it is because since an auto variable is storage class for example is to change the static . 这是因为,因为一个单向auto变量是存储类例如是改变static

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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