dynamic allocation of 2d array

This is a discussion on dynamic allocation of 2d array within the C Programming forums, part of the General Programming Boards category; I need to dynamicly allocate a 2 dimensional array in a function. The parameters that are passed to the function ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  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, 03:25 AM
  3. Dynamic 2d Array
    By lvl99 in forum C Programming
    Replies: 8
    Last Post: 01-01-2009, 09: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21