c - C语言代码的问题

标签 c multidimensional-array

Write a complete program.

  • The program should read two integers: m and n, from the keyboard.
  • Allocate memory for a dynamic 2D m * n array of doubles.
  • Initialize the array according to the formula A[i][j]=(i-5)/(j+1).

我的代码:

#include <stdio.h>
#include <math.h>

int main() {
    int m,n;
    scanf ("%d %d",&m &n);

    double**A=(double**) malloc (m*size of (double*));
    double*B=(double*) malloc (m*n * size of (double));

    for (int i=0;i<n;i++){
        A[i]=B+i*m;
    }

    for (int i=0;i<n;i++){
        for (int j=0;i<m;j++){
            A[i][j]=(i-5)/(j+1);
        }
    }
    free (A);
    free (B);

    return 0;
}

最佳答案

有一些错误:

  • size未定义。
  • #include <math.h>不需要,因为您不调用任何数学函数。
  • 严格来说你应该#include <stdlib.h>正如声明 malloc()和 friend 们。
  • 一个, scanf ("%d %d",&m &n); 中缺失.
  • 无需转换 malloc()返回值。
  • 变量名称始终以小写字母开头。
  • 您有一个}太多了。
  • 缩进和代码格式确实很糟糕,而且是自找麻烦。**
  • ...

检查this section of the C-FAQ查看您是否正确完成了分配。

想法:仔细阅读上面提到的 C-FAQ,它会教给您很多知识,并且会成为宝贵的时间投资。

**这是一个良好的代码缩进和格式设置的示例(没有修复):

int main()
{
    int m;
    int n;

    scanf("%d %d", &m, &n);

    double** A = malloc(m * size of (double*));
    double*  B = malloc(m * n * size of (double));

    for (int i = 0; i < n; i++)
    {
        B[i] = B + i * m;
    }

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; i < m; j++)
        {
            A[i][j] = (i - 5) / (j + 1);
        }
    }

    free(A);
    free(B);

    return 0;
}

好吧,我修复了多余的} .

关于c - C语言代码的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48242807/

相关文章:

c - 关于结构的基本问题

c++ - 如何对图像进行高质量缩放?

python - 减去时间戳的列给我 TypeError

c - 如何仅在一个方向上移动数组元素的位置

javascript - 在多维数组中查找 int 并在 Angular JS 中应用类

c - 我怎样才能使变量盐在 C 的 crypt 函数中使用?

c - 将已定义结构的指针初始化为全局变量

c - 在 C 中将多维数组作为函数参数传递

javascript - 如何在 Angular 中动态生成不同的变量?

arrays - 在numpy中获取3D数组的2D切片的平均值