Thread: dynamic allocation of 2d array

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    36

    dynamic allocation of 2d array

    I need to dynamicly allocate a 2 dimensional array in a function.
    The parameters that are passed to the function are the columns and rows of the matrix.(Do i use malloc, calloc, new...)?

  2. #2
    ---
    Join Date
    May 2004
    Posts
    1,379
    use malloc
    calloc sets the memory to NULL and new/delete is used in C++

    example:
    Code:
    #define X 10
    #define Y 5
    
    /* allocate */
    int i;
    *temp = malloc(sizeof(int*) * X);
    for(i=0;i<X;i++){
      temp[i] = malloc(sizeof(int) * Y);
    } 
    
    /* delete */
    for(i=0;i<X;i++){
      free(temp[i]);
    } 
    free(temp);
    Last edited by sand_man; 05-08-2005 at 09:15 AM.

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    36
    Do I have to define constants?
    Can I use the parameters that are passed to the function to declare the size?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Just search the board - dynamic 2D allocation is a common question - there are plenty of examples to be found.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    ---
    Join Date
    May 2004
    Posts
    1,379
    No they do not have to be constants.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. put matrix from file into 2d dynamic array
    By meriororen in forum C Programming
    Replies: 3
    Last Post: 06-08-2009, 07:51 AM
  2. dynamic 2D array allocation
    By deprekate in forum C Programming
    Replies: 5
    Last Post: 03-03-2009, 04:25 AM
  3. Dynamic 2d Array
    By lvl99 in forum C Programming
    Replies: 8
    Last Post: 01-01-2009, 10:24 AM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM