You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言数组打印程序运行时出现Segmentation Fault(段错误)求修复

C语言数组打印代码段错误修复方案

错误分析

  • 段错误根源:scanf("%d", arr[i]); 中,scanf要求接收变量的地址作为参数,而arr[i]是数组元素的具体值,直接传入会导致非法内存访问,触发Segmentation Fault。
  • 未定义行为:printf("\nThe %d elements are:\n"); 存在格式占位符%d但未传入对应参数n,会导致输出混乱。
  • 函数规范问题:display函数声明返回int类型,但函数体内无return语句,不符合C语言函数规范。

修复后的完整代码

#include <stdio.h>

int display(int arr[], int n);
int main()
{
    int i, n;

    printf("\nEnter the Size of Array:");
    scanf("%d", &n);
    int arr[n];

    printf("\nEnter the %d Values of Arrays", n);
    for (i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);  // 修复:传入元素地址
    }
    display(&arr[0], n);
    return 0;
}

int display(int arr[], int n)
{
    int i;
    printf("\nThe %d elements are:\n", n);  // 修复:补充格式参数n
    for (i = 0; i < n; i++)
    {
        printf("Array [%d]= %d\n", i, arr[i]);
    }
    return 0;  // 修复:添加返回语句,匹配函数声明
}

修复点说明

  • 将scanf("%d", arr[i]); 修改为 scanf("%d", &arr[i]);,确保传入变量地址,让scanf能正确写入数据。
  • 在printf("\nThe %d elements are:\n"); 中补充参数n,修正格式输出的未定义行为。
  • 为display函数添加return 0;语句,匹配函数的int返回类型声明。

内容的提问来源于stack exchange,提问作者Priyanshu Bej

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:03:23