#include<stdio.h> #define M 100 typedef struct { int row; int col; int e; }Triple; typedef struct { Triple data[M + 1]; int m, n, len; }TSMatrix; void InPut(TSMatrix* t); void OutPut(TSMatrix* t); void FastTransposeTSMatrix(TSMatrix A, TSMatrix* B); int main(void) { TSMatrix A; TSMatrix B; InPut(&A); FastTransposeTSMatrix(A, &B); OutPut(&B); return 0; } //读入元素 void InPut(TSMatrix* t) { int i =1; int j = 1; int flag = 1; int row, col, e; printf("请输入所需存取的元素及其位置:\n"); while (flag) { scanf("%d %d %d", &row, &col, &e); if (row != -1) { t->data[i].row = row; t->data[i].col = col; t->data[i].e = e; i++; j++; } else { flag = 0; t->len = j; t->m = 7; t->n = 6; } } } //输出元素 void OutPut(TSMatrix* t) { for (int i = 1; i <= t->len; i++) { printf("%d %d %d\t\n", t->data[i].row, t->data[i].col, t->data[i].e); } } //一次定位快速逆置 void FastTransposeTSMatrix(TSMatrix A, TSMatrix* B) { int col, p, q, t; int num[M]; int position[M]; B->len = A.len, B->n = A.m, B->m = A.n; if (B->len) { //初始化该数组所有元素为0 for (col = 1; col <=A.n; col++) { num[col] = 0; } //计算每一列中非0元素的个数 for (t = 1; t <= A.len; t++) { num[A.data[t].col]++; } position[1] = 1; for (col = 2; col <= A.n; col++) { position[col] = position[col - 1] + num[col - 1]; } for (p = 1; p <= A.len; p++) { col = A.data[p].col; q = position[col]; B->data[q].row = A.data[p].col; B->data[q].col = A.data[p].row; B->data[q].e = A.data[p].e; position[col]++; } } }
这个有可能是数组越界了。
给 num 数组设置更大一些试试有没有错误。比如 int num[M*2]
还是不可以