0

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
        }
    }
1
  • scanf("%lf\t", *(*(m1+i)+j)) to scanf("%lf\t", *(m1+i)+j); and get rid of \t Commented Sep 15, 2014 at 17:03

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.