-1

I'm trying to create an undefined 2D m x m array as global variable. But after I type the m value, I get a

segmentation fail(core image dumped)

error. Can anyone help me with this? Thank you very much. Here's my code:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

double **A;

int main(void) {

    int m, i, j;

    scanf("%d", &m);

    A = (double **)malloc(m * m * sizeof(double));

    for (i = 0; i < m; i++) {
        for (j = 0; j < m; j++) {
            A[i][j] = i + j;
        }
    }

    return 0;
}
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Ericli
  • 11
  • 2

1 Answers1

1

If you want to allocate memory block of size m * m your way then you need to use single pointer arithmetic to access elements.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

double *A;

int main(void) {

    int m;
    scanf("%d", &m);

    A = malloc(m * m * sizeof(double));

    for (int i = 0; i < m; i++) {
        for(int j = 0; j < m; j++) {
            *(A + i * m + j) = i + j;
        }
    }

    return 0;
}

Another way to do this is to use an array of pointers where each pointer points to a memory of size m as explained in here or check the below code

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

double **A;

int main(void) {

    int m;
    scanf("%d", &m) ;

    A = malloc(m * sizeof(double*));

    for(int i = 0; i < m; i++){
        A[i] = malloc(m * sizeof(double));
    }

    for (int i = 0; i < m; i++){
        for(int j = 0; j < m; j++){
            A[i][j] = i + j;
        }
    }

    return 0;
}
dodobhoot
  • 493
  • 6
  • 15