0

I have this array:

float (*probability)[4];

This is 2D array but i don't know the number of first [], this can be calculate in some function after and in that function I don't know how to malloc() this array.

My code is like this:

int main(int argc, char ** argv){
    float (*probability)[4];
    some_function_to_malloc(&probability);
    return 0;
}
pah
  • 4,700
  • 6
  • 28
  • 37

2 Answers2

2

Firstly, float (*probability)[4] is not a 2D array. It is a pointer to a 1D array containing four float. They are different things.

Second, an idiom to use malloc() without introducing unintended type errors is

  probability = malloc(sizeof (*probability) * number_desired);

Doing that in a function with a passed argument will be

 void some_function_to_malloc(float (**probability)[4])
 {
      *probability = malloc(sizeof(**probability) * number_desired);
 }

Don't forget to #include <stdlib.h> in order to use malloc().

Peter
  • 35,646
  • 4
  • 32
  • 74
0

A complete example would be

#include<stdio.h>
#include<stdlib.h>

void malloc_fn(float (**x)[4]){
*x=malloc(sizeof((**x))); // allocating for one int[4]
}
int main(void)
{
int i;
float (*probability)[4];
malloc_fn(&probability);
for(i=0;i<4;i++){
    (*probability)[i]=i; 
    // As pointers support array-style dereferencing,
    // (*(probability+0))[i] is equivalent to probability[0][i]
    // Note we have only allocated memory for one int[4] in our function
    // So probability[1] points to another int[4], which we have not allocated.
    // (*probability)[i]=i; is equivalent to probability[0][i]=i, See printf
}
printf("Printing the array\n");
for(i=0;i<4;i++){
    printf("%f\n",probability[0][i]); // Equivalent to (*probability)[i]
}
return 0;
}
sjsam
  • 21,411
  • 5
  • 55
  • 102