Beginner C/C++

Moderators: None (Apply to moderate this forum)
Number of threads: 5430
Number of posts: 16951

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Dynamic Memory allocation in C Posted by ulka on 9 Jun 2008 at 10:37 AM
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
Report
Re: Dynamic Memory allocation in C Posted by IDK on 9 Jun 2008 at 12:13 PM
See the manual for malloc .
Report
Re: Dynamic Memory allocation in C Posted by Lundin on 9 Jun 2008 at 2:27 PM
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;
  
  free(array_ptr);
}


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.
Report
Re: Dynamic Memory allocation in C Posted by varon89 on 10 Jun 2008 at 8:45 PM
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.

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


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)
            printf("%d\n", arr[20 * row + col]);
}



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.