【发布时间】:2021-02-26 10:25:07
【问题描述】:
我正在编写一个使用数组的程序,但我不确定如何将二维数组从函数传递到 main()。我想在 main() 中从 read_matrix() 函数的输出数组中设置一个二维数组。
void read_matrix();
int main()
{
//reads a matrix from user input
read_matrix();
new_matrix[][] = matrix[n_i][n_i] //I would like to set a new 2d array in main() from the 2d array
//output from the read_matrix() function.
return 0;
}
//reads a matrix from user input
void read_matrix()
{
//initialise variables
int n_i = 0;
int row;
int column;
//dimensions of matrix
printf("Enter a value for the dimensions of a square matrix: \n");
printf(">>");
scanf("%i", &n_i);
//initialise matrix
int matrix[n_i][n_i];
//elements of matrix
for(row = 0; row < n_i; ++row)
{
for(column = 0; column < n_i; ++column)
{
printf("Enter a value for the [%i][%i] element: \n", row, column);
printf(">>");
scanf("%i", &matrix[row][column]);
}
}
}
【问题讨论】:
-
请记住,VLA 被认为是一种不好的做法,您应该查看 malloc 和 free。
标签: c function multidimensional-array