0

I've declared a matrix dynamically as follows

double **y;
y = (double **)malloc(n*sizeof(double *));
for(i=0;i<n;i++)
  y[i]=(double*)malloc(m*sizeof(double));

Where m and n are integers declared before. Then, I need to compute a function that multiplies two different matrix, and I need to check if the number of rows on the first matrix coincides with the number of columns on the second matrix. So I need to know the numbers of columns and rows. So I computed what follows:

int k=sizeof(M[0])/sizeof(double);

But this integer k returns me 1. And no matther how long n and m are...

What am I doing wrong?

Thanks and sorry for my english.

2 Answers2

4

You cannot use sizeof operator on dynamically created array to get array size. If array is created dynamically the only option to know it's size is to store it somewhere.

4pie0
  • 29,204
  • 9
  • 82
  • 118
  • Ok, that makes sense, so which function do I have to use? – Xavier Tapia Gonzalez Mar 23 '16 at 14:56
  • @XavierTapiaGonzalez Which function to use to do what exactly? If you need to allocate memory dynamically and you will need it's size later you must store size of array somewhere. Later you must use these stored values, here m and n. – 4pie0 Mar 23 '16 at 14:57
  • Ok, so is impossible to get the information of the size of a matrix only from the matrix? – Xavier Tapia Gonzalez Mar 23 '16 at 15:01
  • 1
    You are welcome. (A good place to store array dimensions may be introduced array wrapper struct M { double **data; size_t m, n; }) – 4pie0 Mar 23 '16 at 15:11
  • Ok, and you also could send a struct as a variable of a function? In my case for multiplicate matrices "double ** matrix_mult(struct M, struct N)" ? – Xavier Tapia Gonzalez Mar 23 '16 at 15:57
  • @XavierTapiaGonzalez Yes. In this function you would check that number of columns in M is the same as number of rows in N (only number of columns in first matrix must equal number of rows in second) M.n == N.m and perform multiplication on M.data and N.data. – 4pie0 Mar 23 '16 at 16:09
3

Using sizeof(M[0]) only gets you the type size of M[0] which is double * which in your case identical to size of double

So in your case you have to save the size of the allocated array (n, m).

Another solution would be to use stack allocation where sizeof can actually get the size of types like double[]

MoonBun
  • 4,322
  • 3
  • 37
  • 69