简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM