-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;
}
7
  • 3
    You're dereferencing A[i], which is uninitialized. Commented Aug 25, 2018 at 19:48
  • can someone find a good dupe? I'm too tired to google the proper keywords. Commented Aug 25, 2018 at 20:03
  • 1
    what the hell, not the perfect dupe, but ... stackoverflow.com/questions/36890624/malloc-a-2d-array-in-c Commented Aug 25, 2018 at 20:05
  • 1
    Despite what you may think, you are allocating a 1D array, so use double * instead of double **. Access via: A[(i * m) + j] instead of A[i][j] Commented Aug 25, 2018 at 20:21
  • Craig, so how can I do to create a 2D array? Commented Aug 25, 2018 at 20:32

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

also, OP should check that scanf returned a valid value, else m could be 2453463646
You can get the original syntax back by typing the result as pointer-to-array, making the allocated block an array-of-arrays, and keeping the nice multidim syntax OP wanted without needing separate allocations. Your solution is an important step to understanding how that works, though.
yeah, a real 2D access alternative would be a plus. But I understand that you don't want to invest on your answer since you got a really unjustified downvote...
2D access alternative added.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.