Dynamic Memory allocation in C

Hi All
I am in a situation where i need to allocate a dimension of multidimensional array of which remaining dimensions are known at compile time.



how do i allocate the 'row' dimension dynamically.



  • See the manual for malloc .
  • That doesn't makes sense to me. Either you allocate the whole bunch of arrays at runtime, or a much less likely case, all the "inner dimension" arrays exist at compile time and you set a pointer to them in runtime, building up an array of pointers to (possibly multidimensional) arrays.

    The latter version likely origins from flawed logic in the program design... you'd end up with code looking like this:

    #define X 2
    #define Y 10
    #define Z 10

    typedef int (*Array_ptr_type)[Y][Z];

    int main()
    int some_array [Y][Z];
    int some_other_array [Y][Z];

    Array_ptr_type* array_ptr;

    array_ptr = malloc( X * sizeof(Array_ptr_type) );

    array_ptr[0] = &some_array;
    array_ptr[1] = &some_other_array;


    The above implementation is insane in most cases, plus it is hard to read and understand. I am quite certain the specific problem can be solved in a much easier way.
  • It depends. If "int arr[][20]" is declared as an argument of a function, then I don't think that there is a problem; arr gets pointed to some already allocated memory that was pointed to by the array passed as an argument.

    [code]void f(int arr[][20]){};
    int arr_to_pass[2][20];

    If this array is the first to allocate the memory, then you declare
    arr as a pointer and use malloc and pointer arithmetic.
    int main(int rows)
    int *arr = (int*) malloc(rows * 20 * sizeof(int));
    for (int row = 0; row < rows; ++row)
    for (int col = 0; col < 20; ++col)
    ", arr[20 * row + col]);
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!