用c语言用指针写多维数组间的加、减、乘、除运算
时间: 2023-11-27 14:06:24 浏览: 64
首先,我们需要声明多维数组并动态分配内存,这里以两个二维数组A和B为例:
```c
int **A, **B;
int ROWS = 3, COLS = 3;
A = (int **)malloc(ROWS * sizeof(int *));
B = (int **)malloc(ROWS * sizeof(int *));
for (int i = 0; i < ROWS; i++) {
A[i] = (int *)malloc(COLS * sizeof(int));
B[i] = (int *)malloc(COLS * sizeof(int));
}
```
接下来,我们编写加、减、乘、除运算函数:
```c
void add(int **A, int **B, int **C, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}
void subtract(int **A, int **B, int **C, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
C[i][j] = A[i][j] - B[i][j];
}
}
}
void multiply(int **A, int **B, int **C, int rows1, int cols1, int rows2, int cols2) {
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
C[i][j] = 0;
for (int k = 0; k < cols1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
void divide(int **A, int **B, int **C, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
C[i][j] = A[i][j] / B[i][j];
}
}
}
```
最后,我们可以通过调用以上函数来进行多维数组的加、减、乘、除运算:
```c
int **C;
C = (int **)malloc(ROWS * sizeof(int *));
for (int i = 0; i < ROWS; i++) {
C[i] = (int *)malloc(COLS * sizeof(int));
}
// Add
add(A, B, C, ROWS, COLS);
// Subtract
subtract(A, B, C, ROWS, COLS);
// Multiply
int COLS2 = 2;
int **D;
D = (int **)malloc(COLS * sizeof(int *));
for (int i = 0; i < COLS; i++) {
D[i] = (int *)malloc(COLS2 * sizeof(int));
}
multiply(A, B, D, ROWS, COLS, COLS, COLS2);
// Divide
divide(A, B, C, ROWS, COLS);
```
这样我们就可以通过指针来实现多维数组的加、减、乘、除运算了。
阅读全文