【发布时间】:2011-11-07 19:43:14
【问题描述】:
我正在尝试用 C 创建一个简单的矩阵乘法程序。 为此,我选择使用 2 个函数:1 用于简单地创建矩阵,1 用于保存所有创建的矩阵(用于进行乘法运算)。
我终于设法弄清楚如何从函数传递数组(或者更具体地说,从函数传递指向数组的指针),但是,我希望下面的函数 matrixWelcome() 传递行数& 数组的列。这就是我卡住的地方。
目前 gcc 给我错误无效类型参数的“一元 *”行 -> 行 = *i;
我的代码是:
void matrixWelcome() {
int selection;
int a, b, c, d, *rows, *columns;
int *matrix1[0][0], *matrix2[0][0];
printf("Welcome to matrix mode\n");
printf("Please select from the following: \n");
printf("1 - Matrix multiplication");
scanf("%d", &selection);
switch (selection) {
case 1:
printf("Selected matrix multiplication...\n");
printf("Please enter matrix 1\n");
matrix1[*rows][*columns] = matrixInput(*rows, *columns);
printf("%d\n", *matrix1[1][1]);
a = *rows;
b = *columns;
printf("****ROWS = %d, COLUMNS = %d", a, b);
// printf("Matrix 1 has %d rows and %d columns", rows, columns);
printf("Please enter matrix 2\n");
// matrix2 = matrixInput();
break;
default:
printf("No input entered\n");
break;
}
}
int *matrixInput(int *rows, int *columns) {
int i, j, x, y;
int *array_pointer = malloc(5 * sizeof(int)); //grab some memory
if (array_pointer == NULL) { // check that we have successfully got memory
return NULL;
}
// Number of rows & columns for matrix 1
printf("Enter number of rows: ");
scanf("%d", &i);
printf("\nEnter number of columns: ");
scanf("%d", &j);
rows = *i;
columns = *j;
// Initialise 2D array to hold values
int matrix_input[i][j];
printf("Enter values for matrix, starting at 1,1 and moving across 1st row; then move across 2nd row etc..");
// loop to store values in matrix
for (x=0; x<i; x++) {
for (y=0; y<j; y++) {
int value_entered;
scanf("%d", &value_entered);
matrix_input[x][y] = value_entered;
}
}
*array_pointer = matrix_input[i][j];
// print out matrix - just to confirm
printf("You've entered the following matrix: \n");
for (x=0; x<i; x++) {
for (y=0; y<j; y++) {
printf("%4d", matrix_input[x][y]);
}
printf("\n");
}
return array_pointer;
}
任何帮助将不胜感激。
【问题讨论】:
-
w.r.t.标题:请记住,指向对象的指针仅在该对象的生命周期内有效。 (例如,一旦函数返回,指向函数中声明的数组的指针就无效了。)