尝试在 C 中打印值时出现分段错误 [英] Segmentation Fault when attempting to print value in C

查看:15
本文介绍了尝试在 C 中打印值时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 C 代码返回分段错误"错误.我不明白为什么它不返回值 20.我的错误是什么?

The following C code returns a "segmentation fault" error. I do not understand why it does not return the value 20. What is my error?

#include <stdio.h>

int main() 
{
    int* n;
    *n = 20;

    printf("%i
",*n);

    return 0;

}

推荐答案

你还没有给n分配内存,所以

You haven't allocated memory to n, so

*n = 20;

尝试写入未指定的内存.

attempts to write unspecified memory.

试试

#include <stdlib.h>

int *n = malloc(sizeof *n);
/* use n */
free(n);

这篇关于尝试在 C 中打印值时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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