randomboiguyhere
randomboiguyhere

Reputation: 545

Creating a 2D array with malloc and calloc

I am wondering how exactly this works and if this is even the correct way to do this. It works like I want it to. Basically what I'm doing is creating a float array where all elements are 0 with the height of h and width of w.

float** arr = NULL;
arr = (float**) malloc(sizeof(float*) * h);
for (int i = 0; i < h; ++i) {
    arr[i] = (float*) calloc(h, sizeof(float) * w);
}

Upvotes: 1

Views: 530

Answers (1)

tdao
tdao

Reputation: 17668

Assume you want a 2D array - jagged array - with size h x w

Then you need something like:

float** arr = NULL;

size_t h = 2;
size_t w = 3;

arr = (float**) malloc(sizeof(float*) * h);  // 1)
for (size_t i = 0; i < h; ++i) {
    arr[i] = (float*) calloc(w, sizeof(float));  // 2)
}

Note 1) - allocate arr that points to an array size h of pointers to float.

Note 2) - allocate each item arr[i] that points to an array size w of float.

As usual, you should use size_t type instead of int for array size.

Upvotes: 3

Related Questions