繁体   English   中英

2D阵列的动态内存分配(C)

[英]Dynamic memory allocation for 2D arrays (C)

我注意到我缺乏动态2D数组的知识,在这里和网上阅读了一些主题之后,我尝试了一些尝试,但是似乎无法正常工作:我想分配一个3X3整数数组,将输入值分配给它并显示它们,问题是总是在我输入索引[3][1]的值后,程序崩溃了……这很奇怪,因为我认为我正确地完成了所有事情。 我也想听听您关于检查内存分配失败的想法, (!(array))足够好的方法? 我还看到了一些在发生故障之前将内存分配到故障点的示例。

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j, //loop control
    **array, //pointer to hold the 2D array
    N = 3; //rows and columns quantity
array = malloc (N * sizeof (int*)); //allocating rows
if (!(array)) //checking for allocation failure
{
    printf("memory allocation failed!\n");
    goto exit;
}
else
{
    array [i] = calloc (N, sizeof (int)); //allocating columns
    if (!(array[i])) //checking for allocation failure
    {
        printf("memory allocation failed!\n");
        goto exit;
    }
}

for (i = 0; i < N; i++) //getting user input
{
    for (j = 0; j < N; j++)
    {
        printf("Enter value [%d][%d]:", i+1, j+1);
        scanf ("%d", &array [i][j]);
    }
}
for (i = 0; i < N; i++) //displaying the matrix
{
    printf("\n");
    for (j = 0; j < N; j++)
    {
        printf (" %d", array [i][j]);
    }
}
exit:
return 0;

}

您很幸运,它没有更早崩溃。 您只分配了3x3矩阵的一行:

array [i] = calloc (N, sizeof (int)); //allocating columns
if (!(array[i])) //checking for allocation failure
{
    printf("memory allocation failed!\n");
    goto exit;
}

您需要对矩阵的每一行执行此操作,而不仅仅是一次。
此外,当您调用calloci的值是不确定的。 将上面的块包装在foor循环中应该可以解决您的问题:

else
{
    for (i = 0; i < N; i++) {
        array [i] = calloc (N, sizeof (int)); //allocating columns

        if (!(array[i])) //checking for allocation failure
        {
            printf("memory allocation failed!\n");
            goto exit;
        }
    }
}

你有几个问题。

  1. 您正在使用未初始化的i
  2. 您尚未为所有行分配内存。 下一行只能为一行分配内存。

     array [i] = calloc (N, sizeof (int)); //allocating columns 

您需要什么:

代替

array [i] = calloc (N, sizeof (int)); //allocating columns
if (!(array[i])) //checking for allocation failure
{
    printf("memory allocation failed!\n");
    goto exit;
}

采用

for ( i = 0; i < N; ++i )
{
  array [i] = calloc (N, sizeof (int)); //allocating columns
  if (!(array[i])) //checking for allocation failure
  {
      printf("memory allocation failed!\n");
      goto exit;
  }
}

暂无
暂无

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

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