如何在C中使用malloc数组2d

时间:2016-07-19 02:53:47

标签: c arrays

我有这个数组:

float (*probability)[4];

这是2D数组但我不知道第一个[]的数量,这可以在某个函数中计算之后和该函数中我不知道如何malloc()这个数组。

我的代码是这样的:

int main(int argc, char ** argv){
    float (*probability)[4];
    some_function_to_malloc(&probability);
    return 0;
}

2 个答案:

答案 0 :(得分:2)

首先,float (*probability)[4]不是2D数组。它是指向包含四个float的一维数组的指针。它们是不同的东西。

其次,使用malloc()而不引入意外类型错误的习惯是

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

在带有传递参数的函数中执行此操作将是

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

请勿忘记#include <stdlib.h>才能使用malloc()

答案 1 :(得分:0)

完整的例子是

#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;
}