Ryan
Ryan

Reputation: 8241

Initializing C array after malloc'ing memory

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.

Upvotes: 0

Views: 967

Answers (1)

unwind
unwind

Reputation: 399881

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.

Upvotes: 3

Related Questions