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

时间:2014-05-29 19:24:48

标签: c arrays memory-management multidimensional-array

我注意到我缺乏动态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;

}

2 个答案:

答案 0 :(得分:1)

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

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

您需要为矩阵的每个行执行此操作,而不只是一次 此外,当您致电calloc时,i的值未定义。在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 :(得分:1)

你有几个问题。

  1. 您使用的是未初始化的i
  2. 您还没有为所有行分配内存。以下行只能为一行分配内存。

    array [i] = calloc (N, sizeof (int)); //allocating columns
    
  3. 你需要什么:

    而不是

    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;
      }
    }
    
相关问题