-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?

Foufoutos
  • 17
  • 5
  • http://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/ – NiVeR Sep 16 '17 at 18:51
  • 1
    What you have is *not* a 2D array, so try not initialize it like one. – Antti Haapala -- Слава Україні Sep 16 '17 at 18:56
  • BTW, https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc?rq=1 – Jens Sep 16 '17 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. – 0___________ Sep 16 '17 at 19:45
  • @PeterJ_01 Completely contemporary reasons, as spelled out in https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Jens Sep 17 '17 at 18:02
  • @Jens the only real reason does not exists any more as the implicit function declarations are not allowed in the modern C (C99 onwards). It is enough to stop program in the ancient almost 30 years old standard. The rest is just the opinion of the person who answered that question. And as only the opinion based it is not a valid SO answer . – 0___________ Sep 17 '17 at 18:22

1 Answers1

-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

0___________
  • 60,014
  • 4
  • 34
  • 74