[英]dynamically adding two matrices ; error in line 27 and 41
#include<stdio.h>
#include<stdlib.h>
int** addMatrix(int**, int, int, int**);
int main(void)
{
int i, j, m, n, **p, **q, **sum; //i = row, j = column
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<n; i++)
{
p[i] = (int*)malloc(n * sizeof(int));
}
printf("Enter the elements of the Matrix M:\n"); //taking input
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
scanf("%d", ((p+i)+j)); // LINE 27
}
q = (int**)malloc(m * sizeof(int*));
for(i=0; i<n; 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)); // LINE 41
}
sum = addMatrix(p, m, n, q);
printf("Vector Sum:\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
printf("%d ", *(*(sum+i)+j));
printf("\n");
}
}
int** addMatrix(int **p, int m, int n, int **q)
{
int i, j, **add;
add = (int**)malloc(m * sizeof(int*));
for(i=0; i<n; 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;
}
main.c:27:21: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int **' [-Wformat=] main.c:41:21: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int **' [-Wformat=] the lines for taking the input of the matrix. main.c:27:21: 警告:格式 '%d' 需要类型为 'int *' 的参数,但参数 2 的类型为 'int **' [-Wformat=] main.c:41:21: 警告:格式“%d”需要类型为“int *”的参数,但参数 2 的类型为“int **”[-Wformat=] 用于获取矩阵输入的行。 this is the error I am getting.这是我得到的错误。
The for loops like this像这样的for循环
for(i=0; i<n; i++)
{
p[i] = (int*)malloc(n * sizeof(int));
}
are wrong.错了。 You have to use the variable m (the number of rows) instead of n (the number of columns)您必须使用变量 m(行数)而不是 n(列数)
for(i=0; i<m; i++)
{
p[i] = (int*)malloc(n * sizeof(int));
}
The calls of scanf like this scanf 的调用是这样的
scanf("%d", ((p+i)+j));
are also wrong.也错了。
You have to write你必须写
scanf("%d", *(p+i)+j );
The expression *(p+i)+j
is equivalent to p[i] + j
that can be also written like &p[i][j]
.表达式*(p+i)+j
等价于p[i] + j
也可以写成&p[i][j]
。
And you should free all the allocated memory before exiting the program.在退出程序之前,你应该释放所有分配的 memory。
In general you should check whether values for the variables m
and n
are valid and whether memory was allocated successfully.一般来说,您应该检查变量m
和n
的值是否有效以及 memory 是否分配成功。 And it will be better if the variables m
and n
will have an unsigned integer type as for example size_t
instead of the signed integer type int
.如果变量m
和n
具有无符号 integer 类型(例如size_t
而不是带符号的 integer 类型int
)会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.