Thread: Malloc

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    4

    Malloc

    How do i allocate memory to a two-dimentional array ?
    Usually we allocate
    int A[10][10];

    How do we allocate dynamically for above using malloc?

    thanx
    chaitu

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
    	int **i;
    	
    	if ((i = malloc(100*sizeof(int))) == NULL)
    	{
    		perror("malloc");
    		return (1);
    	}
    	i[0][1] = 10;
    	printf("%d\n", i[0][1]);
    	free (i);
    	return (0);
    }
    [EDIT]This is wrong, read all this thread before deciding on what code to use![/EDIT]
    Last edited by Hammer; 05-14-2002 at 04:44 PM.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User bljonk's Avatar
    Join Date
    Oct 2001
    Posts
    70

    sizes and pointers

    int A[x][y];

    if x & y are known:

    int *p = malloc((x*y)*sizeof(int));

    p = &A[0];

    would do the job~, don't forget to free the memory when finished

  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
    Neither of which really implement a 2D array

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int **twod1 ( int row, int col ) {
        int r;
        int **res = malloc( row * sizeof(int*) );
        for ( r = 0 ; r < row ; r++ ) res[r] = malloc( col * sizeof(int) );
        return res;
    }
    
    int main() {
        /* use this if rows and cols are both variable */
        int **a1 = twod1( 10, 10 );
        /* use this if rows is variable, but cols is a compile-time constant */
        int (*a2)[10] = malloc( 10 * sizeof(int[10]) );
        int r, c;
    
        /* show that both support [][] notation */
        for ( r = 0 ; r < 10 ; r++ ) {
            for ( c = 0 ; c < 10 ; c++ ) {
                a2[r][c] = a1[r][c];
            }
        }
        return 0;
    }

  5. #5
    Registered User
    Join Date
    May 2002
    Posts
    4
    I think the last one is correct !!

    thanx a lot
    chaitu

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by chaitu
    I think the last one is correct !!

    thanx a lot
    chaitu
    Actually, either one is correct. You can malloc off a block of 100 integers, and that'll work, you can malloc off 10 pointers to integers, and then malloc 10 blocks of 10 integers. Either one will work.

    Keep in mind that multi-dimensional arrays are actually treated as single dimension arrays. Thus:

    int array[3][3];

    array[1][1] = 10;
    array[4] = 10;

    Both of those two expressions are exactly the same thing.

    012
    345
    678

    See?

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > You can malloc off a block of 100 integers, and that'll work
    Which is exactly what this is
    int (*a2)[10] = malloc( 10 * sizeof(int[10]) );

    But if you do this
    int **a1 = malloc( 100*sizeof(int) );

    Then the code is broken
    Given an array reference like a1[5][2];
    The first step is resolving a1[5], which must be an int* (you started with int**).
    Sure it's within the bounds of the allocated memory, but it isn't an initialised int*, so you're off into no-mans land when you dereference that pointer with a1[5][2]

    You've got to follow the type of the declaration, in order to work out how to initialise it.

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by Salem
    > You can malloc off a block of 100 integers, and that'll work
    Which is exactly what this is
    int (*a2)[10] = malloc( 10 * sizeof(int[10]) );

    But if you do this
    int **a1 = malloc( 100*sizeof(int) );

    Then the code is broken
    Given an array reference like a1[5][2];
    The first step is resolving a1[5], which must be an int* (you started with int**).
    Sure it's within the bounds of the allocated memory, but it isn't an initialised int*, so you're off into no-mans land when you dereference that pointer with a1[5][2]

    You've got to follow the type of the declaration, in order to work out how to initialise it.
    Nod. I should have clarified:

    "You can malloc off a block of 100 integers" means:

    int *array;

    array = malloc( sizeof(int) * 100 );
    array[5][5] = 20;
    array[55] = 30;

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Salem > In your example code you use the two methods of allocating the array. Can you clarify the method used to free them please. I'd like to see the code to complete the picture

    Also, I compiled your code and it crashed when run (as mine did too ). Are you sure it's correct?
    I put some printf's in the for loops to see where it was happening, this is what came out:
    Code:
    ROW :0 
    COL :0  COL :1  COL :2  COL :3  COL :4  COL :5  COL :6  COL :7  COL :8  COL :9  
    ROW :1 
    COL :0  COL :1  COL :2  COL :3  COL :4  COL :5  COL :6  COL :7  COL :8  COL :9  
    ROW :2 
    COL :0
    quzah >
    You mentioned this:
    Code:
    int *array; 
    array = malloc( sizeof(int) * 100 ); 
    array[5][5] = 20; 
    array[55] = 30;
    but my compiler says that's wrong (Invalid indirection). I presume it's due to the derefencing getting messed up as the array is declared as *, not **. In fact, your code here is what I first wrote to answer this post, then found it didn't work so I tweaked it (wrongly!), to have **.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Yeap. I was off in my answer. There are two things:

    1) You can treat an actual two dimensional array as a single dimension array.

    2) You can't treat a single dimension array as a double apparently.

    There is a way to fake it though.

    #define ARRAY(z,x,y) z[(x*ROWS)+(y)]

    I think that's accurate. Or use COLS instead, depending on how you want to use your array.

    ARRAY( myArray, 5, 6 ) = 10;

    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    Comment your source code! Lynux-Penguin's Avatar
    Join Date
    Apr 2002
    Posts
    533
    http://www.rt.com/man/malloc.3.html
    hopefully this explains enough on Malloc so you can use it correctly
    and read at the bottom for other functions like ones to clear memory after it has been allocated.
    Asking the right question is sometimes more important than knowing the answer.
    Please read the FAQ
    C Reference Card (A MUST!)
    Pointers and Memory
    The Essentials
    CString lib

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Can you clarify the method used to free them please
    Code:
    To free
        int **a1 = twod1( ROWS, COLS );
    do this
        for ( r = 0 ; r < ROWS ; r++ ) free ( a1[r] );
        free( a1 );
    
    To free
        int (*a2)[COLS] = malloc( ROWS * sizeof(int[COLS]) );
    do this
        free ( a2 );
    > Also, I compiled your code and it crashed when run
    Not surprised (though kinda surprised it ran here)
    Missed off the return statement (Doh)

    Code:
    int **twod1 ( int row, int col ) {
        int r;
        int **res = malloc( row * sizeof(int*) );
        for ( r = 0 ; r < row ; r++ ) res[r] = malloc( col * sizeof(int) );
        return res;   // MISSING!!!!
    }

  13. #13
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Thanks!
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM