Thread: Dynamically allocate 2D array of ints

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    34

    Dynamically allocate 2D array of ints

    In this problem, I am required to allocate memory ALL AT ONCE. Only one dynamic allocation is allowed. I believe I have code that will allocate all memory needed:

    Code:
    int ** p;
    int cols, rows;
    
    p = (int **)malloc(((rows * sizeof(int *)) + (cols * rows * sizeof(int)))
    cols and rows are passed in as arguments, (let's assume cols = 4, rows = 3). So now I have one big block of memory that will hold 3 pointers to ints which point to the first int in 3 rows of four ints. P will point to my first pointer to int.

    I am having a hard time understanding how to initialize the pointers to ints logically. I believe a looping function is needed. Any advice?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Why go to all that trouble? Are you required to access the element using [two][subscripts]? Why not just allocate memory the way C would, by getting one big block that holds row*col entries?

  3. #3
    Registered User
    Join Date
    Aug 2009
    Posts
    34
    Yes, forgive me for my noobness (if that's not a word, I just coined it), but shouldn't you be able to access any 2 Dimensional pointer array with [two][subscript] notation?

    One requirement of this ASSIGNMENT is that we must only call for one block of memory. Also it will contain a pointer array that points to int arrays, as described in my initial posting.

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    That dual requirement is unfortunate since it makes things about 276 times more complicated than it really needs to be.

    In that case your malloc looks correct. You will then need to initialize your "first dimension" by setting all the pointers to point to the correct places in memory. p[0] should be assigned the start of the "data" portion of the memory (you'll have to get there with pointer arithmetic), then p[1] needs to be assigned the start of the next row (pointer arithmetic), then p[2] the start of the row after that (pointer arithmetic) and so on.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Dynamically Increasing Array of Integers
    By laserlight in forum C++ Programming
    Replies: 30
    Last Post: 07-04-2008, 07:27 AM
  2. Read file in 2D array
    By Chook in forum C Programming
    Replies: 1
    Last Post: 05-08-2005, 12:39 PM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. two dimensional dynamic array?
    By ichijoji in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2003, 04:27 PM
  5. 2d Array access by other classes
    By deaths_seraphim in forum C++ Programming
    Replies: 1
    Last Post: 10-02-2001, 08:05 AM