【问题标题】:Populate Matrix in C with rand()用 rand() 填充 C 中的矩阵
【发布时间】:2017-01-11 16:15:42
【问题描述】:

我试图了解 C 中的矩阵是如何工作的。

我有以下代码:

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

int main(int argc, char* argv[])
{

    /* random number generator for matrix dimensions */
    int xDim, yDim;
    srand(time(NULL)); //init. is needed only once
    xDim = (rand() % (10000+1) + 50);
    yDim = (rand() % (10000+1) + 50);

    /* random number generator for matrix contents */
    double* myMatr;
    myMatr = (double *)malloc(xDim * yDim * sizeof(double));
    for(int i=0; i<xDim; i++)
    {
        for(int y=0; y<yDim; y++)
        {
            myMatr[i][y]= (double)rand()/RAND_MAX*100.0;
        }
    }
}   

但是,我收到此错误:

test.c:24:13: error: subscripted value is neither array nor pointer nor vector
myMatr[i][y]= (double)rand()/RAND_MAX*100.0;

【问题讨论】:

  • myMatr[i]double,所以显然你不能进一步下标。
  • myMatr[i][y] --> myMatr[i * yDim + y]
  • malloc 没有收到 xDim * yDim 规范,只有他们的产品,所以分配的内存不可能被语言解释为二维数组。
  • myMatr 不是二维数组,而是指向double 的指针。这是两个不同的东西。
  • 因为你只定义了一个指针,编译器应该如何能够在myMatr[10][5]myMatr[5][10]之间做出任何区别。只有在所有限制都已知的情况下才能这样做(一维除外)

标签: c matrix random double


【解决方案1】:

对代码的最小更改可能是将myMatr 变成指向数组的指针。

变化:

double *myMatr = (double *)malloc(xDim * yDim * sizeof(double));

(目前在源代码中分布在两行)到:

double (*myMatr)[yDim] = malloc(xDim * yDim * sizeof(double));

然后显示的其余代码可以工作。当然,您应该在末尾添加free(myMatr);

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

int main(void)
{
    srand(time(NULL)); // init. is needed only once

    /* random number generator for matrix dimensions */
    int xDim = (rand() % (10000 + 1) + 50);
    int yDim = (rand() % (10000 + 1) + 50);

    //double *myMatr = (double *)malloc(xDim * yDim * sizeof(double));
    double (*myMatr)[yDim] = malloc(xDim * yDim * sizeof(double));

    /* random number generator for matrix contents */
    for (int i = 0; i < xDim; i++)
    {
        for (int y = 0; y < yDim; y++)
        {
            myMatr[i][y] = (double)rand() / RAND_MAX * 100.0;
        }
    }

    /* print matrix contents */
    for (int i = 0; i < xDim; i++)
    {
        for (int y = 0; y < yDim; y++)
            printf("%6.2f", myMatr[i][y]);
        putchar('\n');
    }

    free(myMatr);
    return 0;
}

【讨论】:

    【解决方案2】:

    在 C 中,a[x][y] 可能意味着几件事:首先,它可能意味着 a 是一个数组或一个指向已知长度数组的指针,声明如下:

    double (*a)[5];
    

    也就是说,a 指向 5 个双精度数组。由于这个大小是提前知道的,您可以分配一个大块并对其进行双重索引。但是,如果您需要在运行时确定两个索引的大小,这将不起作用。在这种情况下,您别无选择,只能将a 声明为指针数组,并分别分配该数组及其每个子数组:

    double **a;
    a = malloc(xDim * sizeof(double *));
    for (int i = 0; i < xDim; i += 1) {
        a[i] = malloc(yDim * sizeof(double));
    }
    

    现在,a[x][y] 的意思是“在数组 a 中找到第 x 个指针,然后在它指向的数组中找到第 y 个 double”。

    【讨论】:

      猜你喜欢
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2013-01-19
      相关资源
      最近更新 更多