在初始化一个二维数组分段故障 [英] Segmentation fault on initializing a 2D array

查看:121
本文介绍了在初始化一个二维数组分段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查我的code正确地雕刻出内存空间,但只要我尝试我的二维数组初始化一些值,然后总结的价值观,我收到的只是一个2×2分割故障数组。我想最终我扩展code到一个更大的数组,但我甚至不能让它工作在这里。我知道有一下有关malloc和二维数组段故障很多帖子,但我一直无法找到一个可以帮助我与我的问题,因为我的C知识才刚刚开始。任何帮助,你可以给,或者如果你可以点我到previous问题将是极大的AP preciated。谢谢!

 的#include<&stdlib.h中GT;
#包括LT&;&stdio.h中GT;
#包括LT&;&math.h中GT;诠释的main()
{
  双总和= 0;
  INT I,J;
  INT N = 2;  双**阵列;
  阵列=的malloc(N * sizeof的(双*)); 如果(阵列== NULL)的printf(未分配内存\\ n); 对于(i = 0; I< = N;我++)
    {
      数组[我] =的malloc(N * sizeof的(双));
      如果(阵列[我] == NULL){
     的printf(无法ARR的内容[%d]分配内存\\ n,I);
     出口(0);
     }
     } 对于(i = 0; I< = N;我++)
  {
    为(J = 0; J< = N; J ++)
  {
    数组[I] [J] = 1.0 /(I + J);
    总和=总和+阵列[I] [J]。
   }
   }   返回(0);
 }


解决方案

您已经牺牲品经典的失误之一:使用< = ,而不是<

 为(i = 0; I< = N;我++)

这将初始化数组[0]数组[1],最重要的阵列[2](因为2'= 2)。三个三分球,但你没有malloc的空间,只有两个

下面是你想要的:

 为(i = 0; I< N;我++)

有将通过阵列迭代[0]和阵列[1](总共两个条目的)。

(不是说你没有其他错误,但是这绝对是其中之一。)

I've checked that my code is properly carving out memory space, but as soon as I try to initialize my 2D array to some values and then sum up the values, I receive a segmentation fault on just a 2x2 array. I would like to eventually scale my code up to a much larger array, but I can't even get it working here. I know there are many posts about segmentation fault regarding malloc and 2D arrays, but I've been unable to find one that helps me with my problems since my C knowledge is just beginning. Any help that you can give or if you can point me to a previous question would be greatly appreciated. Thank you!

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int main()
{
  double sum=0;
  int i,j;
  int N = 2;

  double **array;
  array = malloc(N * sizeof(double *));

 if(array == NULL) printf("Failure to allocate memory.\n");

 for(i=0; i<=N; i++)
    {
      array[i] = malloc(N * sizeof(double));
      if(array[i] == NULL) {
     printf("Failed to allocate memory for arr[%d].\n", i);
     exit(0);
     }
     }

 for(i=0; i<=N; i++)
  {
    for(j=0; j<=N; j++)
  {
    array[i][j] = 1.0/(i+j);
    sum = sum + array[i][j];
   }
   }

   return(0);
 }

解决方案

You've fallen victim to one of the classic blunders: Using <= instead of < .

for(i=0; i<=N; i++)

That will initialize array[0], array[1], and MOST IMPORTANTLY array[2] (because 2 <= 2), but you didn't malloc space for three pointers, only two.

Here's what you want:

for(i=0; i<N; i++)

It will iterate through array[0] and array[1] (for a total of two entries).

(Not saying you don't have other bugs, but that's definitely one of them.)

这篇关于在初始化一个二维数组分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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