开发者

dynamic array in c

开发者 https://www.devze.com 2023-02-07 07:15 出处:网络
I want after I do some calculation create an array in C wouldu pl开发者_运维技巧ease help me? int len_arr = (sizeof inputs)/(sizeof inputs[0]);

I want after I do some calculation create an array in C would u pl开发者_运维技巧ease help me?

int len_arr = (sizeof inputs)/(sizeof inputs[0]);
int half_arr = len_arr / 2;
if(len_arr%2 != 0)
    half_arr++;

int m[half_arr][half_arr];


I'm assuming you wish to create a matrix with row/column size of half_arr.

int i;
int len_arr = (sizeof inputs)/(sizeof inputs[0]); 
int half_arr = len_arr / 2; 
if(len_arr%2 != 0)     
    half_arr++;  

int **m = malloc(half_arr * sizeof(int));

for (i = 0; i < half_arr; i++)
    *m = malloc(half_arr * sizeof(int));

You should then be able to access m using m[row][column] or m[column][row].


You need to use malloc to allocate your 2-dimensional array.

Look at this LINK for a good explanation.


EDIT:

Starting from the code at the given link, I've written a piece of code that should work.

Some differences from James' code:

  • declaration of m at the top of the code block
  • conversion from the return type of malloc (void *) to the correct one
  • memory deallocation at the end
  • it's a complete code, that must work :P

#include <stdlib.h>

int main ()
{

    // just an example of inputs...
    int inputs[3][7];

    // your code
    int i;
    int **m;
    int len_arr = (sizeof inputs)/(sizeof inputs[0]); 
    int half_arr = len_arr / 2; 
    if(len_arr%2 != 0)     
        half_arr++;  

    // allocation of the array
    m = (int **)malloc(half_arr * sizeof(int *));
    for(i = 0; i < half_arr; i++)
        m[i] = (int *)malloc(half_arr * sizeof(int));

    // use the array as you like...
    // ...

    // let's release the allocated memory properly
    for(i = 0; i < half_arr; i++)
        free(m[i]);
    free(m);

}


Your code is valid C99. You might want to use a compiler which supports newer revisions of the C language.

On Windows, I'd go with the MinGW edition of gcc. If you're stuck with MSVC, I suggest using C++ instead: the standard container types will make your life less painful.

0

精彩评论

暂无评论...
验证码 换一张
取 消