动态添加两个矩阵:代码第27、41行存在类型不匹配警告
矩阵加法代码的类型不匹配警告解决方法
问题根源
你代码中第27行和第41行的scanf参数类型错误:
scanf("%d", ((p+i)+j)); // LINE 27 scanf("%d", ((q+i)+j)); // LINE 41
p是二级指针(int**),p+i表示指向第i行的指针(类型仍是int**),(p+i)+j会让指针偏移j个int*的字节长度,最终传递给scanf的参数类型是int**,但%d格式符要求接收一个int*类型的地址,因此触发类型不匹配警告。
修正方案
获取矩阵第i行第j列元素的地址,有两种正确写法:
- 指针解引用写法:
*(p+i) + j(先拿到第i行的一级指针,再偏移j个int位置) - 数组下标写法(更直观易读):
&p[i][j]
修正后的读取代码片段:
// 读取矩阵M的元素 printf("Enter the elements of the Matrix M:\n"); for(i=0; i<m; i++) { for(j=0; j<n; j++) scanf("%d", &p[i][j]); // 替换原第27行 } // 读取矩阵N的元素 printf("Enter the elements of the Matrix N:\n"); for(i=0; i<m; i++) { for(j=0; j<n; j++) scanf("%d", &q[i][j]); // 替换原第41行 }
额外修正:内存分配的越界问题
你代码中分配矩阵行内存的循环条件存在错误,以矩阵p为例:
for(i=0; i<n; i++) // 错误:循环次数是列数n,实际应为行数m { p[i] = (int*)malloc(n * sizeof(int)); }
p是存储m行的指针数组,应该循环m次分配每行的内存,否则当m≠n时,会出现内存分配不足或越界访问问题。修正为:
for(i=0; i<m; i++) { p[i] = (int*)malloc(n * sizeof(int)); }
同理,矩阵q和add的行内存分配循环也需要做同样修正。
完整修正后的代码
#include<stdio.h> #include<stdlib.h> int** addMatrix(int**, int, int, int**); int main(void) { int i, j, m, n, **p, **q, **sum; printf("Enter the size of the row: "); scanf("%d", &m); printf("Enter the size of the col: "); scanf("%d", &n); p = (int**)malloc(m * sizeof(int*)); for(i=0; i<m; i++) { p[i] = (int*)malloc(n * sizeof(int)); } printf("Enter the elements of the Matrix M:\n"); for(i=0; i<m; i++) { for(j=0; j<n; j++) scanf("%d", &p[i][j]); } q = (int**)malloc(m * sizeof(int*)); for(i=0; i<m; i++) { q[i] = (int*)malloc(n * sizeof(int)); } printf("Enter the elements of the Matrix N:\n"); for(i=0; i<m; i++) { for(j=0; j<n; j++) scanf("%d", &q[i][j]); } sum = addMatrix(p, m, n, q); printf("Matrix Sum:\n"); for(i=0; i<m; i++) { for(j=0; j<n; j++) printf("%d ", sum[i][j]); printf("\n"); } // 释放动态分配的内存,避免内存泄漏 for(i=0; i<m; i++){ free(p[i]); free(q[i]); free(sum[i]); } free(p); free(q); free(sum); return 0; } int** addMatrix(int **p, int m, int n, int **q) { int i, j, **add; add = (int**)malloc(m * sizeof(int*)); for(i=0; i<m; i++) { add[i] = (int*)malloc(n * sizeof(int)); } for(i=0; i<m; i++) { for(j=0; j<n; j++) add[i][j] = p[i][j] + q[i][j]; } return add; }
(注:额外添加了内存释放代码,同时简化了矩阵元素访问语法,提升可读性)
内容的提问来源于stack exchange,提问作者RC5413
相关产品推荐
相关产品推荐

