Howdy, Stranger!

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

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Dynamic Memory allocation in C

ulkaulka Posts: 17Member
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.

e.g.

arr[][20];

how do i allocate the 'row' dimension dynamically.

ulhas

Comments

  • IDKIDK Posts: 1,784Member
    See the manual for malloc .
  • LundinLundin Posts: 3,711Member
    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:

    [code]
    #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;

    free(array_ptr);
    }[/code]

    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.
  • varon89varon89 Posts: 3Member
    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]){};
    main
    {
    int arr_to_pass[2][20];
    f(arr_to_pass)
    }[/code]

    If this array is the first to allocate the memory, then you declare
    arr as a pointer and use malloc and pointer arithmetic.
    [code]
    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)
    printf("%d
    ", arr[20 * row + col]);
    }[/code]
Sign In or Register to comment.