0

So i'm trying to allocat an array to hold a matrix of floats. the values passed in are ints (rows and cols) and the function is a pointer. so this is my function definition:

float *matrix(int rows,int cols)
{
    int i=0;
    float *m=NULL;
    m=(float *)malloc(rows*sizeof(int));
    for (i=0;i<rows;i++)
    {
        m[i]=(float*)malloc(cols*sizeof(int));
    }   
}

i have a feeling that this is wrong. i also get an error when i try to run. where exactly is the problem here? should the int be a float instead?

edit****

float *matrix(int rows,int cols)
{
    int i=0;
    float **m=NULL;
    m=(float *)malloc(rows*sizeof(float));
    for (i=0;i<rows;i++)
    {
        m[i]=(float *)malloc(cols*sizeof(float));
    }
}

alright if malloc doesn't run properly and fails i wan't to return NULL. so it should be this code here, right?

if(m[i]==NULL)
{
    return NULL;
}
nm10563
  • 43
  • 1
  • 9

1 Answers1

1
    int i=0;
    float **m; // You are looking for a pointer to pointer to float
    m=malloc(rows*sizeof(float*)); //Step1
    for (i=0;i<rows;i++)
    {
        m[i]=malloc(cols*sizeof(float)); //Step2
    }   

Notes

  1. You need not the cast the output of malloc for the reason mentioned in [ this ] answer.
  2. In step1, you allocate memory for rows float*s
  3. For each of the float* in step1, we allocate memory to store cols floats in step2
Community
  • 1
  • 1
sjsam
  • 21,411
  • 5
  • 55
  • 102