I'm trying to write a matrix multiplication program that takes in an int N on command line, creates two NxN matrices A & B, randomly populates them with ints, and then computes the result of multiplying A and B.

I wanted to avoid malloc, but the first version started segfaulting at around N = 850:

int N = atoi(argv[1]);

  /* create two int[N][N] matrices, a & b */
  int a[N][N];  
  int b[N][N];  

  /* populate a and b with random ints */
  srand(time(NULL));
  int i; //tracks row
  int j; //tracks col
  int k; //tracks index
  for (i=0; i<N; i++) {
    for (j=0; j<N; j++) {
      a[i][j] = rand() % 10;
      b[i][j] = rand() % 10;
    }
  } 

  /* multiply a and b to get result */
  int result[N][N];
  for (i=0; i<N; i++) {   
    for (j=0; j<N; j++) {      
      for (k=0; k<N; k++) {
	result[i][j] += a[i][k] * b[k][j];
      }				
    }
  }

If anyone knows how to make the above code work for higher values of N, please enlighten me! I then tried the below:

typedef struct {
  int *data;
} Matrix;

Matrix *A, *B, *R;
 A = (Matrix *) malloc(sizeof(A));
 B = (Matrix *) malloc(sizeof(B));
 R = (Matrix *) malloc(sizeof(R));

  for (i=0; i<N; i++) {
    for (j=0; j<N; j++) {
      A->data[i*N+j] = rand() % 10;
      B->data[i*N+j] = rand() % 10;
    }
  }

  for (i=0; i<N; i++) {
    for (j=0; j<N; j++) {
      int sum = 0;
      for (k=0; k<N; k++)
	sum += A->data[i*N+k] * B->data[k*N+j];
      R->data[i*N+j] = sum;
    }
  }

But I can't get this to work at all. I think I probably screwed up the structs and pointers to structs, but checking K&R and Googling for examples hasn't helped me fix it. Any help would be greatly appreciated. Thanks a lot in advance!

Edited 6 Years Ago by thm: n/a

You are asking malloc to supply you enough space to hold 'A', which is a pointer to a structure that requires a pointer. You need to allocate data for the 'data' pointer inside your Matrix class.

You are asking malloc to supply you enough space to hold 'A', which is a pointer to a structure that requires a pointer. You need to allocate data for the 'data' pointer inside your Matrix class.

I'm sorry, I don't know how to do that. I tried revising to

A = (matrix *) malloc(N*N*sizeof(int));
 B = (matrix *) malloc(N*N*sizeof(int));
 R = (matrix *) malloc(N*N*sizeof(int));

and then

A->data = (int *) malloc(N*N*sizeof(int));
 B->data = (int *) malloc(N*N*sizeof(int));
 R->data = (int *) malloc(N*N*sizeof(int));

but I'm still wrong...

This question has already been answered. Start a new discussion instead.