-2

I'm trying to dive a little bit into C programming. So I'm trying to create a 2-d array using double pointers and initializing it with random values. However during the access phase it throws a segmentation fault

Below is a striped down snippet of my code:

int main(void){

// Memory allocation for arrays

int size = 3;

double **matrix = (double **)malloc(sizeof(double *)*size*size);

int i, k;

for(i=0; i<size; i++){
      for(k=0; k<size; k++){
        matrix[i][k]  = ((double)rand())/1314.7;
      }
}

return 0;
}

Could you please point me what am I doing wrong?

6
  • geeksforgeeks.org/dynamically-allocate-2d-array-c Commented Sep 16, 2017 at 18:51
  • 1
    What you have is not a 2D array, so try not initialize it like one. Commented Sep 16, 2017 at 18:56
  • BTW, stackoverflow.com/questions/605845/… Commented Sep 16, 2017 at 18:58
  • @Jens completely outdated reasons. There is nothing wrong nowadays in casting unless you program in the prehistoric C standard. If one ignores warnings - will ignore all of them anyway. Commented Sep 16, 2017 at 19:45
  • @PeterJ_01 Completely contemporary reasons, as spelled out in stackoverflow.com/questions/605845/… Commented Sep 17, 2017 at 18:02

1 Answer 1

-1

This the pointer to pointer table, you need the table of doubles :)

double *matrix = malloc(sizeof(double)*size*size);

int i, k;

for(i=0; i<size; i++){
      for(k=0; k<size; k++){
        matrix[i * size + k]  = ((double)rand())/1314.7;
      }
}

or for **

double **matrix = malloc(sizeof(double *)*size);

for(int i = 0; i < size; i++)
    *(matrix + i) = malloc(sizeof(double) * size);

for(i=0; i<size; i++){
      for(k=0; k<size; k++){
        matrix[i][k]  = ((double)rand())/1314.7;
      }
}

of course in the real code you need to check if malloc did not fail etc etc

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

3 Comments

None of that your show (without explaining, btw.) is a 2D array. OP wants a 2D array, so he should use one.
Not clear what he wants. I saw *s and mallics. So I have gone the pointer way. @Olaf you of course know better :D
How does using a pointer/dynamic allocation prevent using a 2D array?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.