2d array pointers...

am i doing this right? im assigning random values to Matrix a & b using a pointer, then trying to print out the first value in matrix a...not doing something right, i am getting segmentation fault

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <stdlib.h>
using namespace std;

const int SIZE = 100;
typedef double Matrix[SIZE][SIZE];

int main()
  {
    Matrix *a;
    Matrix *b;
    Matrix *c;
    for (int i = 0; i < SIZE; i++)
      {
        for (int j = 0; j < SIZE; j++)
          {
            srand(time(NULL));
            *a[i][j] = rand() % 100;
            *b[i][j] = rand() % 100;
          }
      }
    cout << *a[0][0] << endl;
  }
compiles fine, just won't run
Is there a reason why you use pointers here? Try without.
as you use srand() function you should include #include<ctime> ..
I think you need to put the [SIZE] beside the variables, not the type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <stdlib.h>
using namespace std;

const int SIZE = 100;
typedef double Matrix;

int main()
  {
    srand(time(NULL));
    Matrix *a[SIZE][SIZE];
    Matrix *b[SIZE][SIZE];
    Matrix *c[SIZE][SIZE];
    for (int i = 0; i < SIZE; i++)
      {
        for (int j = 0; j < SIZE; j++)
          {
            *a[i][j] = rand() % 100;
            *b[i][j] = rand() % 100;
          }
      }
    cout << *a[0][0] << endl;
  }


If you want to avoid rewriting size over and over, you could make a struct:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <stdlib.h>
using namespace std;

const int SIZE = 100;
struct Matrix
  {
    double matrix[SIZE][SIZE];
  };

int main()
  {
    srand(time(NULL));
    Matrix *a;
    Matrix *b;
    Matrix *c;
    for (int i = 0; i < SIZE; i++)
      {
        for (int j = 0; j < SIZE; j++)
          {
            *a.matrix[i][j] = rand() % 100;
            *b.matrix[i][j] = rand() % 100;
          }
      }
    cout << *a.matrix[0][0] << endl;
  }


Oh, it doesn't cause your problem, but it will cause problems:
Put srand at the top of main. It needs to be called exactly once in a code. Any more and you'll start to see non-random behavior.
Last edited on
sweet thanks lol
Topic archived. No new replies allowed.