-1

I want to initialize a n*n square matrix to later pass it by reference into another function. But it doesn't even compile. I've tried everything, please help.

#include<stdlib.h>
int main()
{
    int i, j, n = 3;
    float **a;
    a = malloc(n * sizeof (float **));//Here I try to create the n pointers to pointer to float for the rows
    for(i = 1;i <= n;i++){
        a[i] = malloc(n * sizeof(float *)); //Here I try to create the n * n pointers to float for the columns
    for(j = 1;j <= n;j++)
        *(*(a + i - 1) + j - 1) = malloc(sizeof(float));  //Here I try to free the space for the elements
    return 0;
}
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
Ivanz
  • 15
  • 1
  • 5

2 Answers2

2

you need to declare it like this :

float **a;
a = malloc(n * sizeof (float *)); // rows
for(i = 0;i < n;i++){
        a[i] = malloc(n * sizeof(float)); // cols
}
chouaib
  • 2,763
  • 5
  • 20
  • 35
0

Your code shows something different to what your comment suggests you are trying to do.

Here I try to create the n * n pointers to float for the columns

Normally a 2-D "array" of float has N x N floats - not N x N pointers to float. You are making a 3-D "array" where the innermost dimension is 1.

Also you are using the wrong type in your sizeof expressions , so you malloc the wrong amount of memory.

Please clarify whether a 2-D "array" is what you want, or if you really do need the extra level of indirection in your code. (I'll update my answer after that).

(NB. I say "array" in quotes as we are not talking about a true multidimensional array; it is in fact an array of pointers which point to the first element of arrays of float (or in the 3-D case, which point to an array of pointers which point to a float).

M.M
  • 138,810
  • 21
  • 208
  • 365
  • @Ivanz you mean you want an array of pointers to arrays of float? (a "2D array" would be `float a[n][n];`) – M.M Jun 13 '14 at 00:06
  • I'm not quite sure what I answered, but OK..:) – M.M Jun 13 '14 at 00:23
  • "Normally a 2-D "array" of float has N x N floats - not N x N pointers to float. You are making a 3-D "array" where the innermost dimension is 1." Bullseye – Ivanz Jun 13 '14 at 00:30