简体   繁体   English

初始化2D阵列时出现分段错误

[英]Segmentation fault on initializing a 2D array

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. 我已经检查过我的代码正确地划分了内存空间,但是一旦我尝试将我的2D数组初始化为某些值然后总结这些值,我就会在2x2数组上收到分段错误。 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. 我知道关于malloc和2D数组有很多关于分段错误的帖子,但由于我的C知识刚刚开始,我一直无法找到一个帮助我解决问题的帖子。 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. 这将初始化array [0],array [1]和MOST IMPORTANTLY数组[2](因为2 <= 2),但是你没有三个指针的malloc空间,只有两个。

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). 它将遍历数组[0]和数组[1](总共两个条目)。

(Not saying you don't have other bugs, but that's definitely one of them.) (不是说你没有其他的错误,但这绝对是其中之一。)

You're allocating space for an NxN array, but in your for cycles, you're trying to access an (N+1) by (N+1) array. 你正在为NxN数组分配空间,但在你的for循环中,你试图访问(N + 1)by(N + 1)数组。 You can replace your cycles by one of the following: 您可以通过以下方法之一替换您的周期:

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

or 要么

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

Given that you are calculating 1.0/(i+j) , you may use the second one, because the first will produce a division by zero when i=0, j=0. 假设您正在计算1.0 /(i + j) ,则可以使用第二个,因为当i = 0,j = 0时,第一个将产生除零。 But beware, if you use the second option you should shift your indexes by 1, like this: array[i-1][j-1] , because these will always start at 0. It is better to use the first option. 但要注意,如果你使用第二个选项,你应该将索引移动1,如下所示: array [i-1] [j-1] ,因为它们总是从0开始。最好使用第一个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM