印刷指向整数导致分段错误。为什么? [英] Printing pointer to integer causes segmentation fault. Why?

查看:94
本文介绍了印刷指向整数导致分段错误。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
main()
{
    int *num2=20;
    printf("\n\n\n%d",num2);
}

当我运行它,因为它是,它打印 20 。如果我使用 * NUM2 它会导致分段错误。为什么呢?

When I run it as it is, it prints 20. If I use *num2 it causes segmentation fault. Why?

推荐答案

当你说,为int * NUM2 = 20; 。它相当于

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. */

二):

int *num = malloc(sizeof *num);
*num = 20; 

这篇关于印刷指向整数导致分段错误。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆