[英]Create 2d Array using Pointer of pointers
我正在尝试使用指针指针制作2D数组,并且碰到了墙。 尝试扫描要存储在第一矩阵中的值时,我的程序崩溃(第38行)。 我想在m1[i][j]
和m1[i][j] == *(*m1+i)+j
的地址中存储一个值吗?
我提供了以下代码(直到崩溃为止)。 这里发生了什么? 为什么在扫描矩阵1的输入时崩溃?
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
int main() {
//Initializing variables
int i= 0, j = 0, m = 0, n = 0, p = 0, q = 0;
double **m1, **m2, **mr;
//Prompt user to enter dimensions of first matrix.
printf("Enter number of rows and columns of 1st matrix:");
scanf("%d %d",&m,&n); //Scanning user input
//Prompt user to enter dimension of second matrix.
printf("Enter number of rows and columns of 2nd matrix:");
scanf("%d %d",&p,&q); //Scanning input
//Check if cols (matrix 1) and rows (matrix 2) are equal
if(n!=p)
printf("Not possible");
//If M1 cols == M2 rows allocate memory for matrices
else {
m1 = malloc(sizeof(double *) * m);
for( i=0; i < m; i++)
m1[i] = calloc(n, sizeof(double));
m2 = malloc(sizeof(double *) * p);
for( i=0; i < p; i++)
m2[i] = calloc(q, sizeof(double));
mr = malloc(sizeof(double *) * m);
for( i=0; i < m; i++)
mr[i] = calloc(q, sizeof(double));
//Prompt user to enter values for matrix 1
printf("Enter 1st matrix values:");
//For loop for number of rows
for(i=0;i<m;i++) {
//For loop for number of cols
for(j=0;j<n;j++) {
scanf("%lf\t", *(*(m1+i)+j)); //Scanning input
}
}
//Prompt user to enter values for matrix 2
printf("Enter 2nd matrix values:\n");
for(i=0;i<p;i++) {
for(j=0;j<q;j++) {
scanf("%lf", &(*(m2+i)+j)); //Scanning input
}
}
这行是不对的:
scanf("%lf\t", *(*(m1+i)+j)); //Scanning input
*(*(m1+i)+j)
是double
,而不是double*
,这是scanf
所需要的。
您需要使用
scanf("%lf\t", *(m1+i)+j); //Scanning input
或更简单的形式:
scanf("%lf\t", &m1[i][j]); //Scanning input
在其他循环中,您也有类似的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.