gpt4 book ai didi

c - 尝试获取指向 int 的指针时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:08 25 4
gpt4 key购买 nike

尝试运行下面的代码时出现段错误

#include <stdio.h>


int main(){

int* tes1;
int* tes2;

*tes1=55;

*tes2=88;



printf("int1 %p int2 %p \n",tes1,tes2);

return 0;
}

这是为什么?

最佳答案

你需要分配指针,否则它们指向垃圾内存:

int* tes1; //random initial value
int* tes2; //random initial value

为了使它们指向可分配的内存,使用malloc函数:

int* tes1 = malloc(sizeof(int)); //amount of memory to allocate (in bytes)
int* tes2 = malloc(sizeof(int));

然后你安全地使用指针:

*tes1=55;
*tes2=88;

但是当你完成后,你应该使用 free 函数释放内存:

free(tes1);
free(tes2);

这会将内存释放回系统并防止内存泄漏。

关于c - 尝试获取指向 int 的指针时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15858777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com