1

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);
}
5
  • 1
    That is a good way to create a jagged array. Commented Dec 7, 2019 at 11:32
  • @Someprogrammerdude That's not really what I was going for here though Commented Dec 7, 2019 at 11:34
  • A jagged array doesn't have to be "jagged". You can still use it as a "2d" array or a matrix. Commented Dec 7, 2019 at 11:36
  • @Someprogrammerdude Okay but that doesn't really answer my question.. Is this the correct way to create a 2d array of floats where every element is equal to zero? Commented Dec 7, 2019 at 11:38
  • It's one way to do it. Commented Dec 7, 2019 at 11:39

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is what I was looking for, thanks. Quick question, would it be fine to use arr = (float**) calloc(h, sizeof(float*));?
Yes, the effect is the same. But use malloc in the first call would be more efficient because you don't really need to zero out the content of arr[i] pointer, you only need to clear the content of what arr[i] points to. In other words, the 2nd call to calloc is necessary, but the 1st is not.

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.