【问题标题】:2d dynamic array program crashes二维动态数组程序崩溃
【发布时间】:2015-01-28 03:35:25
【问题描述】:

我编写了一个动态分配的 2D 数组,但由于某种原因它没有按我的预期工作。 我分配了一个 14x5 数组来存储值。

代码如下:

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

int main()
{
   int i, j, count, count2;
   int size, keysize, column;

   size = 7;  keysize = 10; column = 5;
   int row = (size * keysize) / column;  // 14

   char **arr = (char **)malloc(column * sizeof(char *));
   for(i=0; i<row; i++)
      arr[i] = (char *)malloc(row * sizeof(char *));

   count=0;
   count2=0;

   for(i=0; i<keysize; i++)
   {
      for(j=0; j<size; j++)
      {
         printf("arr[%d][%d]=", count2, count);
         arr[count2][count] = 'C';
         printf("%c\n", arr[count2][count]);
         count++;

         if(count == 5)
         { 
            count = 0;
            count2++;
         }
      }
   }
   return 0;
}

在 arr[6][0] 位置插入值时,程序似乎崩溃了。 在此之前它工作正常。 我插入了一些 printf 语句来捕捉这种情况。

我不知道为什么会这样,内存分配对我来说看起来不错,但我不是专家。

感谢您的帮助。

【问题讨论】:

  • 注意:请避免转换malloc()的返回
  • arr[i] = (char *)malloc(row * sizeof(char *));。您应该分配(rows * elementsize),但目前还不清楚有多少行或每个元素的大小。
  • column = 5; malloc(column * sizeof(char *)); 这为 5 个指向行的指针腾出空间,然后您调用 arr[6][0],这样它将访问数组末尾。
  • @SouravGhosh 他同时拥有 C 和 C++ 标签,如果他想用 C++ 编译器编译它,他需要强制转换它,C++ 不会隐式地进行任意指针类型转换。 (我知道这是不可取的,但有些人只是编写在 C++ 和 C 编译器上编译的程序)
  • @PeterT #include &lt;stdio.h&gt; 和 malloc() 不适用于 C++。此外,同时标记C 和c++ 通常被认为是标签垃圾邮件。

标签: c++ c arrays malloc


【解决方案1】:

我注意到标有 c++ 标记的问题,在 c++ 中执行此操作的明确方法是使用 std::vector。所以我回答这个问题就好像它是一个 C 问题:

您似乎没有在此处分配足够的空间。

column = 5;
char **arr = (char **)malloc(column * sizeof(char *));

这为 5 个指向行的指针腾出空间。然后在您循环播放时:

for(i=0; i<keysize; i++)//note keysize is 10
{
    for(j=0; j<size; j++){ // note size is 7
        arr[count2][count];
        count++;
        if(count == 5){
            count = 0;
            count2++;//gets incremented every time the inner loop runs
        }
    }
}

因为每次内部循环运行时count2 都会递增,所以它最终会变得与keysize 一样大。这意味着arr[keysize][0] 必须是有效的,这并不是因为您实际上创建了arr[5][14]。第一个失败是当您调用 arr[6][0] 时,它访问数组末尾并导致程序崩溃。

如果这里的目的是初始化变量,那么要解决这个问题,您可能需要循环遍历用于分配内存的维度的相同值。

【讨论】:

    【解决方案2】:

    改成

    char **arr = (char **)malloc(row * sizeof(char *));
    for(i=0; i<row; i++)
       arr[i] = (char *)malloc(column * sizeof(char));
    

    【讨论】:

      猜你喜欢
      • 2015-06-05
      • 2019-08-11
      • 1970-01-01
      • 2012-10-09
      • 2015-08-22
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多