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;
}