c - 初始化二维数组时出现段错误

标签 c segmentation-fault malloc multidimensional-array

我已经检查过我的代码是否正确地分配了内存空间,但是当我尝试将我的 2D 数组初始化为某些值然后对这些值求和时,我仅在 2x2 数组上收到段错误。我想最终将我的代码扩展到更大的数组,但我什至不能让它在这里工作。我知道有很多关于 malloc 和 2D 数组的段错误的帖子,但是由于我的 C 知识才刚刚开始,所以我一直无法找到可以帮助我解决问题的帖子。如果您能提供任何帮助,或者如果您能指出我之前的问题,将不胜感激。谢谢!

#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);
 }

最佳答案

您已成为经典错误之一的受害者:使用 <=而不是 < .

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

这将初始化 array[0]、array[1] 和最重要的 array[2](因为 2 <= 2),但是您没有为三个指针分配空间,只有两个。

这是你想要的:

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

它将遍历数组[0] 和数组[1](总共有两个条目)。

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

关于c - 初始化二维数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19059151/

相关文章:

c - 是使用任何未定义的不确定值还是仅使用存储在具有自动存储的对象中的值?

c - 在用户输入字符串上使用 strlen 时出现段错误

c++ - 无法为堆栈框架生成反汇编,因为无法翻译 URL & 段错误 : 11

c - 错误: Conflicting types in structs pointers

C 中内存读写的自定义处理

c - 文件读取并存储为 C 中的 int

c++ - 在 Windows 屏幕上渲染缓冲区

Python 等同于 Bit Twiddling Hacks 中的 C 代码?

android - Android 上的 GStreamer x264enc 和 SIGSEGV

multithreading - 寻求帮助, "error: GC operation on unregistered thread. Thread registered implicitly."