Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 尝试打印数组的第一个值时出现分段错误_C_Segmentation Fault - Fatal编程技术网

C 尝试打印数组的第一个值时出现分段错误

C 尝试打印数组的第一个值时出现分段错误,c,segmentation-fault,C,Segmentation Fault,这是我的代码: #include <stdio.h> #include <stdlib.h> int * get_arr(int max_val) { int arr[max_val]; arr[0] = 1; printf("%d\n", arr[0]); return arr; } // a function that appears to have nothing to do with i and pt int some_oth

这是我的代码:

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


int * get_arr(int max_val) {
    int arr[max_val];
    arr[0] = 1;
    printf("%d\n", arr[0]);
    return arr;
}

// a function that appears to have nothing to do with i and pt
int some_other_function() {
    int junk = 999;
    return junk;
}

int main () {

    int *pt = get_arr(10); 
    printf("access before: %d\n", *pt);

    // try this program with and without this function call 
    some_other_function();


    printf("but if I try to access i now via *pt I get %d\n", *pt);
    printf("here\n");
    return 0;
}

我仍然在这里得到一个分段错误
printf(“但是如果我现在通过*pt尝试访问I,我得到了%d\n”,*pt)。知道我为什么会出现分段错误吗?

您需要将arr的值放在堆上,而不是堆栈上。调用
some\u other\u function()
时,arr的值将被覆盖,因为另一个函数已结束,分配的内存不再保证存在

试试这个:

int * get_arr(int max_val) {
    int *arr = malloc(sizeof(int) * max_val);
    arr[0] = 1;
    printf("%d\n", arr[0]);
    return arr;
}

只需记住调用
free(pt)
当您使用完数组时。

编译器警告:“返回局部变量的地址。”当
get\u arr
返回时,
arr[]
不再存在。@WeatherVane但我认为当将数组作为参数传递时,会传递指向数组第一个元素的指针?@WeatherVane也在
some\u other\u函数()之后)
被调用时,
*pt
是否应该指向
999
?您没有传递数组,您返回的指针已超出范围,变量
arr
不再存在,但调用方使用它时就好像它确实存在一样。不,它不存在。由于
arr
不再存在,因此它所指向的内容未定义。
int * get_arr(int max_val) {
    int *arr = malloc(sizeof(int) * max_val);
    arr[0] = 1;
    printf("%d\n", arr[0]);
    return arr;
}