无法将值分配给变量和指针 [英] Can't assign values to variable and pointer
问题描述
我是C语言的新手,但是不知道为什么该程序会中断.如果删除与i
有关的行,则程序会编译并运行,但是如果分配i
,则在程序不中断的情况下,无法再将任何内容分配给*ptr
.
I'm very new to C, but have no idea why this program breaks. The program compiles and runs if I remove the lines that have to do with i
, but if I assign i
, I can no longer assign anything to *ptr
without the program breaking.
int main(void)
{
int i;
int *ptr;
i = 2;
*ptr = 5;
printf("%d",*ptr);
}
推荐答案
您将指针保留未初始化的值.因此,当您取消引用(*ptr
)时,会访问内存中的任意位置,从而导致分段错误.
You leave the pointer with uninitialized value. So when you dereference it (*ptr
), you access arbitrary place in memory, resulting in a segmentation fault.
通过将变量(例如&i
)或一些新分配的内存(例如malloc(sizeof(int))
)的地址分配给ptr
本身(而不是*ptr
),将ptr
指向某处.
Point ptr
at something by assigning to ptr
itself (not *ptr
) an address of a variable (like &i
) or some freshly allocated memory (like malloc(sizeof(int))
).
这篇关于无法将值分配给变量和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!