简体   繁体   中英

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. My program crashes as soon as I try to scan in values to store in 1st matrix (line 38). I want to store a value in the address of m1[i][j] and m1[i][j] == *(*m1+i)+j correct?

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?

#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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM