[英]Create 2d Array using Pointer of pointers
I am trying to make a 2d array using a pointer of pointers and have hit a wall. 我正在尝试使用指针指针制作2D数组,并且碰到了墙。 My program crashes as soon as I try to scan in values to store in 1st matrix (line 38).
尝试扫描要存储在第一矩阵中的值时,我的程序崩溃(第38行)。 I want to store a value in the address of
m1[i][j]
and m1[i][j] == *(*m1+i)+j
correct? 我想在
m1[i][j]
和m1[i][j] == *(*m1+i)+j
的地址中存储一个值吗?
I have supplied the code below (up until the point of crashing). 我提供了以下代码(直到崩溃为止)。 What is going on here?
这里发生了什么? Why is it crashing when scanning in input for matrix 1?
为什么在扫描矩阵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
}
}
This line is not right: 这行是不对的:
scanf("%lf\t", *(*(m1+i)+j)); //Scanning input
The type of *(*(m1+i)+j)
is double
, not double*
, which is what you need for scanf
. *(*(m1+i)+j)
是double
,而不是double*
,这是scanf
所需要的。
You need to use 您需要使用
scanf("%lf\t", *(m1+i)+j); //Scanning input
or, a simpler form: 或更简单的形式:
scanf("%lf\t", &m1[i][j]); //Scanning input
You have similar errors in the other loops. 在其他循环中,您也有类似的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.