如何创建一个二维数组,其维度由用户指定? (在C)
这是我的尝试。我不完全肯定我用指针操作。也许这就是为什么我错了,也许还有其他一些情况。我想从用户那里获取维度并创建一个矩形矩阵,对其元素进行一些操作,并将原始结果和结果显示给用户。上次我通过创建一个100x100数组来完成这个任务,并且通过常量指定每行的结尾和行尾。然后,我会打印所有元素达到这个常量。但为4x4矩阵创建100x100阵列似乎并不正确。我可以创建一个更小的阵列,但这似乎不是解决问题的正确方法。有没有办法在C创建一个完全由用户指定大小的二维数组(它将是一个方形数组)。谢谢如何创建一个二维数组,其维度由用户指定? (在C)
#include <stdio.h>
#include <stdlib.h>
double * createMatrix(int dimentions);
void drawMatrix(double * matrix);
int main(void)
{
int n, i, j;
system("cls");
system("color 70");
system("pause");
puts("Enter the matrix's dimension");
scanf("%i", &n);
double * pmatrix = createMatrix(n);
for (i = 0; i < n; ++j)
for (j = 0; j < n; ++j)
{
printf("A%i%i: ", i + 1, j + 1);
scanf("%lf", pmatrix[i][j]);
getchar();
}
for (i = 0; i < n; ++i)
{
putchar('\n');
for (j = 0; j < n; ++j)
printf(" %lf ", &pmatrix[i][j]);
}
system("color 08");
return 0;
}
double * createMatrix(int n)
{
const int N = n;
const int N1 = N;
double matrix[N][N];
double * pmatrix = matrix;
return pmatrix;
}
您可以直接创建矩阵;你不需要这个功能。通过声明一个2-d阵列中的常规方式替换码
double * pmatrix = createMatrix(n);
:使用指针做它的
double matrix[n][n];
我在想这件事,现在我试试 – sasha199568 2014-10-07 17:26:29
它工作起来,我从一开始就想过,但是我在某处读到C中不可能的东西,或者我的老师告诉过我。下次我要测试新的信息。 – sasha199568 2014-10-07 17:50:46
另一种方式。
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
double **pmatrix;
int rowsize, colsize, i, j;
printf("Enter the number of rows: ");
scanf("%d",&rowsize);
printf("Enter the number of columns: ");
scanf("%d",&colsize);
//Allocate memory for 2D array
pmatrix = malloc(rowsize*sizeof(double*));
for(i=0;i<rowsize;i++)
{
pmatrix[i] = malloc(colsize*sizeof(int));
}
//Accepting the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("A %i %i: ", i + 1, j + 1);
scanf("%lf",&pmatrix[i][j]);
}
}
//Printing the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("%lf\t",pmatrix[i][j]);
}
printf("\n");
}
//Free the memory
for(i=0;i<rowsize;i++)
free(pmatrix[i]);
free(pmatrix);
return 0;
}
C中没有办法创建具有运行时维的标准二维数组。它必须动态完成。 – wallyk 2014-10-07 16:57:53
@wallyk type arr [a] [b];其中a和b是局部变量。 – 2501 2014-10-07 16:58:37
你现在的代码有什么问题? – gaurav5430 2014-10-07 17:00:28