为什么我的代码出现分段错误(核心转储)错误? [英] Why my code give segmentation fault(core dumped) error?

查看:40
本文介绍了为什么我的代码出现分段错误(核心转储)错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用0作为每个数组索引的内容初始化一个5x5数组.但是,每当我运行我的代码时,我都会遇到分段错误(核心转储错误).您能帮我解决我的代码有什么问题吗?我的代码如下.

I want to initialize a 5x5 array with 0 as content of each array index. But whenever i run my code, i get segmentation fault(core dumped error). Can you please help me what is the problem with my code. My code is as follows.

#include <stdio.h>
int main()
{
    int a[5][5];
    int i,j;
    for(i=0; i<=5; i++)
    {
        for(j=0; j<=5; j++)
        {
            a[i][j]=0;
        }
    }
}

推荐答案

您有一个由5行(索引为0..4)和5 cols(索引为0..4)组成的数组,但是您正在访问6行(索引)0..5)和6列(索引0..5).您需要调整循环的边界.

You have an array of 5 rows (indexed 0..4) and 5 cols (indexed 0..4), but you are accessing 6 rows (indexes 0..5) and 6 cols (indexes 0..5). You need to adjust the bounds on your loop.

#define ROWS 5
#define COLS 5

int a[ROWS][COLS];
for (int i=0; i<ROWS; ++i) {
    for (int j=0; j<COLS; ++j) {
        a[i][j] = 0;
    }
}

也就是说,您可以简单地使用以下代码来初始化数组:

That said, you could simply use the following to initialize the array:

#define ROWS 5
#define COLS 5

int a[ROWS][COLS] = { 0 };

请注意,我使用名称而不是在各处使用硬编码数字.这样可读性更强,更不容易出错.

Note that I used names rather than hardcoding the numbers everywhere. This is far more readable and far less error-prone.

这篇关于为什么我的代码出现分段错误(核心转储)错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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