打印指向整数的指针会导致分段错误.为什么? [英] Printing pointer to integer causes segmentation fault. Why?
问题描述
#include<stdio.h>
main()
{
int *num2=20;
printf("
%d",num2);
}
当我按原样运行它时,它会打印 20
.如果我使用 *num2
它会导致分段错误.为什么?
When I run it as it is, it prints 20
. If I use *num2
it causes segmentation fault. Why?
推荐答案
为什么打印 num
没问题,但 *num
导致分段错误?
当你说,int *num2=20;
.相当于
Why printing num
was okay but *num
resulted in segmentation fault?
When you say, int *num2=20;
. It is equivalent to
int *num; /* Type:(int*) num is a pointer to an integer and hence holds address of an integer object. */
num = 20; /* Type of the value assigned to num is (int).*/
您将 int
分配给 int *
.你应该收到一个
You are assigning int
to int *
. You should have received a
warning: initialization makes pointer from integer without a cast[enabled by defaut]
num
指向地址20
".即使那是一个有效地址,你也不知道.
num
points to the address '20
'. You have no idea even if that is a valid address.
因此,当您仅打印 num
时,您没有任何问题.但是取消引用,地址(20
)是无效的内存读取,导致未定义的行为,并导致分段错误.
Hence when you printed just num
you had no problems. But dereferencing, the address(20
) is invalid memory read , causes undefined behaviour and that resulted in segmentation fault.
num
应该包含一个有效的地址.不要冒险自己分配一些随机地址.
num
should hold a valid address. Do not take this risk by assigning some random address yourself.
通过创建 int
类型的对象并分配 num
来保存它的地址或为此分配内存来避免这种风险.喜欢,
Avoid that risk by either creating an object of type int
and assign num
to hold the address of it or just allocate memory for that. Like,
i):
int var = 20; /* var is a integer object holding the value 20 */
&
一元运算符可帮助您获取操作数的地址.使用 &
和 var
来获取它的地址,因为 var
是一个整数,所以将它存储在一个整数指针中.在你的情况下,num
.
&
unary operator helps you get the address of the operand. Use &
with var
to get its address and since var
is an integer, store it in an integer pointer. In your case, num
.
int *num = &var; /* num is a pointer to var. Holds the address of var. */
ii):
int *num = malloc(sizeof *num);
*num = 20;
这篇关于打印指向整数的指针会导致分段错误.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!