0

I'm trying to make a function that generates random matrixes.

I'm not great at pointers but i really thought this should work.

Here's my function that I call twice from main, and that generates the same matrix in both cases...

int **generate_matrix(size_t m, size_t n){
int i1,i2;

int **ptr1=(int **)malloc(sizeof(int *)*m);

srand(time(0));
for(i1=0; i1<m; i1++){
    ptr1[i1] = (int*)malloc(sizeof(int)*n);
    for(i2=0; i2 < n; i2++){
        ptr1[i1][i2]=rand()%10;
    }
 }
return ptr1;
}

In main i call them in a normal way:

int **matrix1,**matrix2;
matrix1=generate_matrix(3,3);
matrix2=generate_matrix(3,3);
(...)
//prints and stuff
free(matrix1);
free(matrix2);
João Pereira
  • 673
  • 1
  • 9
  • 29
  • What do you mean it generates same matrix? How can this be possible with `rand()` and `malloc()` – Gopi Dec 09 '14 at 11:13
  • And what is the problem? – Iharob Al Asimi Dec 09 '14 at 11:14
  • Well, I don't know. Thing is..it does return the same matrix. It looks like the second pointer is pointing at the same matrix as the 1st generated pointer – João Pereira Dec 09 '14 at 11:15
  • 1
    This is *not* a 2D array that you are using but an array of pointers. Mondern C can easily allocate real 2D matrices and compute with them, even dynamically, something like `int (*mat)[m] = malloc(sizeof(int[n][m]));` would do. Also, you shouldn't cast the return of `malloc`, https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Jens Gustedt Dec 09 '14 at 11:38

1 Answers1

2

You are seeding your rand with srand(time(0));. If your calculations are fast enough (i.e. the next second is not reached) time will return the same value twice due to its granularity of 1s.

You could check your results by seeding with definitely different numbers.

Dawnkeeper
  • 2,844
  • 1
  • 25
  • 41
  • That answer sent me in the right direction. Instead of putting `srand(time(0))` in `generate_matrix()` I do it only once in the beginning of `main()`. Thank you for your help – João Pereira Dec 09 '14 at 11:39