0

I need to initialize a 2D array in C after dynamically allocating memory for it. I'm allocating memory as follows:

double **transition_mat = (double **) malloc(SPACE_SIZE * sizeof(double *));

for (int i = 0; i < SPACE_SIZE; i++) {
    transition_mat[i] = (double *) malloc(SPACE_SIZE * sizeof(double));
}

but then I want to initialize it to a certain 2D array, similar to the way initialization can be done when storing the array on the stack:

double arr[2][2] = {{1.0, 7.0}, {4.1, 2.9}};

However, after allocating memory in the first code segment, trying to do assignment as follows produces an error:

transition_mat = (double **) {{1.0, 7.0}, {4.1, 2.9}};

Does anyone know of a clean way to initialize arrays after malloc'ing memory?

Note: someone suggested that I loop over 0 <= i < SPACE_SIZE and 0 <= j < SPACE_SIZE and assign values that way. The problem with that is that the entries cannot simply be computed from i and j, so that code ends up looking no cleaner than any brute force method.

2
  • The loop is the only way to do it. Unless you memcpy from a preexisting array. Commented Sep 17, 2015 at 7:21
  • OT: In C it is not needed, nor recommended to cast functions returning void-pointers. Commented Sep 17, 2015 at 9:40

1 Answer 1

3

If you're going to have all the data as literals in the code (to do the initialization), why not just store that as an explicit 2D array to begin with, and be done?

Worst case, do the dynamic allocation and copy from your existing array.

Make it static const inside the function, or at global scope, depending on the access pattern you need.

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

2 Comments

Do you mean store it as an explicit 2D array outside of the function? If my understanding is correct, when initializing an array by double arr[2][2], it is stored on the stack, not the heap, so I cannot pass it into another function as an argument (which I need to do).
Of course you can pass things stored on the stack inside a function to another function, as long as that call is from within the first function.

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.