【发布时间】: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]之间做出任何区别。只有在所有限制都已知的情况下才能这样做(一维除外)