二维数组矩阵相乘代码
时间: 2023-11-12 20:17:06 浏览: 117
以下是一个用C语言编写的二维数组矩阵相乘的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int rows;
int columns;
int **elements;
} TwoDArray, *TwoDArrayPtr;
TwoDArrayPtr initTwoDArray(int rows, int columns) {
TwoDArrayPtr arrayPtr = (TwoDArrayPtr)malloc(sizeof(TwoDArray));
arrayPtr->rows = rows;
arrayPtr->columns = columns;
arrayPtr->elements = (int**)malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
arrayPtr->elements[i = (int*)malloc(columns * sizeof(int));
}
return arrayPtr;
}
void matrixMultiply(TwoDArrayPtr paraPtr1, TwoDArrayPtr paraPtr2, TwoDArrayPtr *resultPtr) {
if (paraPtr1->columns != paraPtr2->rows) {
printf("矩阵不能相乘.\r\n");
*resultPtr = NULL;
return;
}
*resultPtr = initTwoDArray(paraPtr1->rows, paraPtr2->columns);
for (int i = 0; i < paraPtr1->rows; i++) {
for (int j = 0; j < paraPtr2->columns; j++) {
int sum = 0;
for (int k = 0; k < paraPtr1->columns; k++) {
sum += paraPtr1->elements[i][k * paraPtr2->elements[k][j];
}
(*resultPtr)->elements[i][j = sum;
}
}
}
int main() {
TwoDArrayPtr arrayPtr1, arrayPtr2, resultPtr;
// 初始化两个矩阵
arrayPtr1 = initTwoDArray(2, 3);
arrayPtr2 = initTwoDArray(3, 2);
// 对两个矩阵赋值
// 矩阵相乘
matrixMultiply(arrayPtr1, arrayPtr2, &resultPtr);
// 打印结果矩阵
for (int i = 0; i < resultPtr->rows; i++) {
for (int j = 0; j < resultPtr->columns; j++) {
printf("%d ", resultPtr->elements[i][j]);
}
printf("\n");
}
// 释放内存
free(arrayPtr1);
free(arrayPtr2);
free(resultPtr);
return 0;
}
```
这段代码使用了结构体`TwoDArray`来表示二维数组,并定义了`initTwoDArray`函数来初始化二维数组。`matrixMultiply`函数用于计算两个矩阵的乘积,并将结果存储在`resultPtr`指针指向的内存中。最后,在`main`函数中进行了相应的操作和打印结果。
请注意,这只是一个示例代码,具体的实现可能因编程语言或具体需求而有所不同。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [数据结构-C语言代码 day9-二维数组与矩阵乘法](https://blog.csdn.net/yydslty/article/details/124866964)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [如何将一个二维数组和一个三维数组矩阵相乘得到一个三维数组?](https://blog.csdn.net/weixin_42561476/article/details/112899444)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文