【发布时间】:2014-09-15 16:56:38
【问题描述】:
我正在尝试使用指针的指针创建一个二维数组并碰壁。一旦我尝试扫描值以存储在第一个矩阵(第 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)) 到 scanf("%lf\t", *(m1+i)+j);并摆脱 \t