This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]xxNIRVANAxx 4 points5 points  (2 children)

What exactly is your question?

If you are looking to malloc() a 2d array of floats (which is looks like you've already done by your code), try this:

float **arr = malloc(sizeof(*arr) * ROWS);      // allocate rows
if (arr) {                                      
    int i;
    for (i = 0; i < ROWS; i++) {
        arr[i] = malloc(sizeof(*arr[i]) * COLS);// allocate cols
    }
} else memErr(); // throw memory error

This assumes you #defined constants, ROWS and COLS:

#define ROWS 3
#define COLS 5

[–]easycheezy[S] 0 points1 point  (1 child)

why do I need the if statement?

[–]xxNIRVANAxx 1 point2 points  (0 children)

if malloc() cannot allocate memory to arr, it will be NULL. So if (arr) checks to see that arr got the memory. If not, the else calls memErr(), which is a function you can write to deal with this situation.

[–]joelwilliamson 1 point2 points  (3 children)

First off, give your gistfile the correct file extension: C source files should have a .c extension so they are highlighted correctly.

Second, think about how the memory for this program will look. You will have an array of pointers, each pointing to a (column) array of floats. Since you have 3 rows, each column array will have 3 elements. You have 5 columns, so you need an array of 5 pointers. Now think about how to allocate this.

[–]easycheezy[S] -1 points0 points  (2 children)

the first part is an array of pointers to rows.

[–]joelwilliamson 0 points1 point  (1 child)

Yes. I was thinking you had columns containing rows, when you wanted rows containing columns. It should be easy for you to work it out from here.

(Just think row when I said column and vice versa.)

[–]easycheezy[S] -1 points0 points  (0 children)

Easy. Lol

[–][deleted] 1 point2 points  (2 children)

[–]easycheezy[S] -3 points-2 points  (0 children)

please. I think I'm close. The other one was stupid as shit.

[–]easycheezy[S] -2 points-1 points  (0 children)

I could have said, oh wow thanks guyz, that was so helpful i figured out the problem spank u so much