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;
}
1
  • A float* isn't an array of float*s. Commented Jul 2, 2016 at 2:52

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.