首页 > 解决方案 > C 中的 Malloc 和锯齿状数组

问题描述

我编写了一个打印二项式系数金字塔的程序。问题是当我使用 Xcode 编译和运行代码时它会正确打印它们,但是当我在终端中这样做时它会打印错误的数字。我希望有人能告诉我为什么会这样。我在 macOS Mojave 上运行最新版本的 Xcode。

更新:重新启动 Xcode 后,我也没有得到 Xcode 上系数的正确数字。


这是代码:

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

/* Function prototype */

int C(int a, int b);

int main(){
  int count =0;
  int n = 0;        /* The number of rows in the array (minus 1)  */


  /* Prompt user to input and validate */

  printf("Please enter a positive integer:\n"
         "n = ");
  do
    scanf("%d", &n);
  while ( n <= 0 );


  /* Allocate enough memory for the matrix */

  int **matrix = (int**) malloc( (n+1) * sizeof(int*) );


  /* Allocate enough memory for each array */

  for (int i = 0; i < n+1; i++) {
    matrix[i] = (int*) malloc( (i+1) * sizeof(int) );
  }


  /* Populate each array */

  for (int i = 0; i < n+1; ++i) {
    for (int j = 0; j < i+1; ++j) {
      matrix[i][j] = count;
      count++;
    }
  }


  /* Print pyramid */

  for (int i = 0; i < n+1; ++i) {
    for (int j = 0; j < i+1; ++j) {
      if ( (i==0) && (j==0) ) {
        for (int k = 0; k < n+1-i; ++k) {
          printf("\t");
        }
        printf("%d\n", matrix[i][j]);
      }
      else
        if (j == 0) {
          for (int k = 0; k < n+1-i; ++k) {
            printf("\t");
          } printf("%d\t", matrix[i][j]);
        } else
          if ( (0 < j) && (j < i) ) {
            printf("\t%d\t", matrix[i][j]);
          }
          else
            if (j == i) {
              printf("\t%d\n", matrix[i][j]);
            }
    }
  }


  /* Free allocated memory */

  free(matrix);

  return 0;
}


/************************ Function Definition **********************/

/*
 * Function: C
 * -----------
 * Computes the binomial coefficient via the factorial formula, using
 * for-loops for the factorials.
 *
 * f_a = the factorial of the first number
 * f_b = the factorial of the other number
 * f_a_b = the factorial of the difference (a-b)
 *
 * returns: the binomial C = (a,b)
 */

int C(int a, int b) {
  unsigned int f_a = 1;
  unsigned int f_b = 1;
  unsigned int f_a_b = 1;


  for ( int i = 1; i < a; ++i ) {
    f_a *= i;
  }
  for ( int i = 1; i < b; ++i ) {
    f_b *= i;
  }
  for ( int i = 1; i < (a-b); ++i ) {
    f_a_b *= i;
  }

  unsigned int C = f_a / ( f_b * f_a_b );
  return C;
}

标签: cxcode

解决方案


您计算阶乘的方式是错误的:

for ( int i = 1; i < a; ++i )

应该

for ( int i = 1; i <= a; ++i )

因为你必须包括最后一个元素。这就是定义阶乘的方式。

此外,此函数更适合计算二项式系数,因为阶乘在13(使用 32 位 int 时)溢出。

int C(int a, int b)
{
    int bc = 1; 

    if (b > a-b) 
    {
       b = a-b;
    }

    for (int i = 0; i < b; i++) 
    { 
        bc *= (a - i); 
        bc /= (i + 1); 
    } 

    return bc; 
}

推荐阅读