1
我可以掃描矩陣並確定大小,但輸出爲空白。找到矩陣的所有元素等於座標(i + j)的總和
這裏是我的代碼:
int createTripplesArrayAndList(int** mat, int row, int colum, Tripple **arr, Node** ls) {
int i, j, count=0, k = 0;
Node* head = *ls;
Node* tmp=NULL;
//count how many elements would be in the required array\list
for (i = 0; i < row; i++) {
for (j = 0; j < colum; j++) {
if (mat[i][j] == i + j) {
count++;
}
}
}
//going over the matrix and add the relevant elements to the array and to the list
(*arr) = (Tripple*)calloc(count, sizeof(Tripple));
for (i = 0; i < row; i++) {
for (j = 0; j < colum; j++) {
if (mat[i][j] == i + j) {
//add element to array
(*arr)[k].argument = mat[i][j];
(*arr)[k].i = i;
(*arr)[k].j = j;
//add element to the list
if (!head) {
tmp = (Node*)malloc(sizeof(Node));
tmp->value = (*arr)[k];
tmp->next = NULL;
head = tmp;
} else {
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->value = (*arr)[k];
new_node->next = NULL;
head->next = new_node;
head = new_node;
}
k++;
}
}
}
*ls = tmp;
return count;
}
void printTrripleArrAndList(Tripple* arr, int n, Node** ls) {
int i, j;
Node* curr = *ls;
printf("The tripple list is: ");
while (curr != NULL) {
printf("%d+%d=%d ->", curr->value.i, curr->value.j, curr->value.argument);
curr = curr->next;
}
printf("\nThe tripple array is: ");
for (i = 0; i < n; i++) {
printf("%d+%d = %d\n", arr[i].i,arr[i].j,arr[i].argument);
}
}
int ** createMat(int*n,int*m) {
int** mat = NULL;
int i, j, row, column;
//allocate and the matrix
printf("please enter size of row and colum: ");
scanf("%d%d", &row, &column);
mat = (int**)calloc(row, sizeof(int*));
for (i = 0; i < row; i++) {
mat[i] = (int*)calloc(column, sizeof(int));
}
//fill the matrix
printf("enter numbers for the matrix: ");
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
scanf("%d", &mat[i][j]);
}
}
*n = row;
*m = column;
return mat;
}
我曾經碰到一個錯誤說類型節點*的值不能被分配到類型列表的實體*,所以我不得不他們都更改爲節點*的問題區域爲:
head-> next = new_node;
and:
curr = curr-> next;
請幫忙。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define M 2
#define N 3
#define R 4
typedef struct Tripple {
int i;
int j;
int argument;
} Tripple;
typedef struct Node {
Tripple value;
struct Node* next;
} Node;
int* powerArray(int n);
void printPowArr(int* p, int n);
int** MatrixMultiplication(int firstMat[M][N], int secondMat[N][R]);
void printMatrix(int** p);
int createTripplesArrayAndList(int** mat, int row, int colum, Tripple **arr, Node** ls);
void printTrripleArrAndList(Tripple* arr, int n, Node** ls);
int** createMat(int* n, int*m);
這是我的主:
void main() {
int *p;
int** newMat;
int p1[M][N] = { { 1, 4, 2 }, { 0, 3, 1 } };
int p2[N][R] = { { 1, 3, 1, 4 }, { 0, 2, 6, 4 }, { 4, 1, 0, 7 } };
int **mat=NULL;
int count;
int n = 0, m = 0, i = 0, j = 0;
p = powerArray(10);
printPowArr(p, 10);
newMat = MatrixMultiplication(p1, p2);
printMatrix(newMat);
Tripple* arr=NULL;
Node* ls=NULL;
mat=createMat(&n,&m);
count = createTripplesArrayAndList(mat, n, m, &arr, &ls);
printTrripleArrAndList(arr, count, &ls);
system("pause");
}