Like Tree3Likes
  • 1 Post By oogabooga
  • 1 Post By MK27
  • 1 Post By brewbuck

Making 2D array with malloc()

This is a discussion on Making 2D array with malloc() within the C++ Programming forums, part of the General Programming Boards category; so I'm trying out some used in malloc and generally understand how to use it for 1d arrays, but having ...

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    117

    Making 2D array with malloc()

    so I'm trying out some used in malloc and generally understand how to use it for 1d arrays, but having trouble with 2d arrays.

    So I just want to to create a 2d array with all 1's. Would also be great to differentiate the first array from the second. I.e. first array has 3 second has 10;

    Thanks!!

    Code:
    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        int ** test;
        int size = 3;
        test = (int**) malloc (size*sizeof(int));
    
        for(int o = 0; o<size; o++)
        {
            for(int i=0;i<size;i++)
            {
                test[o][i] = 1;
                cout << test[o][i];
            }
        }
        return 0;
    }
    My Ctrl+S addiction gets in the way when using Code Blocks...

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    1,620
    Think of it as "an array of arrays". Space has to be allocated and freed for the outer one as well as all of the inner arrays.
    Devoted my life to programming...

  3. #3
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    There's a couple ways to do it. See the first couple of examples here.
    MK27 likes this.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  4. #4
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,649
    If you're writing C++, shouldn't you be using new? If you still want to use malloc, you should be including cstdlib. And try to avoid using o as a variable name; too easily mistaken for a 0.

  5. #5
    Registered User
    Join Date
    Sep 2011
    Posts
    117
    Quote Originally Posted by oogabooga View Post
    There's a couple ways to do it. See the first couple of examples here.

    I'm getting an error:
    Code:
    C:\Documents and Settings\Jon\My Documents\2d malloc\main.cpp||In function 'int main()':|
    C:\Documents and Settings\Jon\My Documents\2d malloc\main.cpp|11|error: invalid conversion from 'void*' to 'int**'|
    C:\Documents and Settings\Jon\My Documents\2d malloc\main.cpp|13|error: invalid conversion from 'void*' to 'int*'|
    ||=== Build finished: 2 errors, 0 warnings ===|
    here is the code:
    Code:
    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        int i, o, ncolumns = 2, nrows = 3;
    
    	int** test = malloc(nrows * sizeof(int*));
    	for(i = 0; i < 2; i++)
    		test[i] = malloc(ncolumns * sizeof(int));
    
    
        for(o = 0; o<nrows; o++)
        {
            for( i=0;i<ncolumns;i++)
            {
                test[o][i] = 1;
                cout << test[o][i];
            }
        }
        return 0;
    }

    Quote Originally Posted by rags_to_riches View Post
    If you're writing C++, shouldn't you be using new? If you still want to use malloc, you should be including cstdlib. And try to avoid using o as a variable name; too easily mistaken for a 0.
    Is there any advantage? I'm thinking I might want to use malloc() bc CUDA uses it.
    My Ctrl+S addiction gets in the way when using Code Blocks...

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Malloc returns a void pointer. In C, this is automagically compatible with any type. In C++, you have to cast it to type:

    Code:
    int** test = (int**)malloc(nrows * sizeof(int*));
    Is there any advantage?
    In this case, not particularly, but in general it is a bad habit to use malloc/free in C++ because new/delete deal with objects (constructors and destructors) properly whereas the C functions do not.
    Last edited by MK27; 03-12-2012 at 05:43 PM.
    JonathanS likes this.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Sep 2011
    Posts
    117
    very nice, it works but is a bit funky

    if i put this code, it exits with -1073741819 (0xC0000005)

    Code:
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    int main()
    {
        int i, o, ncolumns = 2, nrows = 3;
    
        int** test = (int**)malloc(nrows * sizeof(int*));
    	for(i = 0; i < 2; i++)
    		test[i] = (int*)malloc(ncolumns * sizeof(int));
    
    
        for(o = 0; o<=nrows; o++)
        {
            for( i=0;i<=ncolumns;i++)
            {
                test[o][i] = 1;
                cout << test[o][i];
            }
        }
    
        return 0;
    }
    but if i put this, it just completely errors...
    Code:
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    int main()
    {
        int i, o, ncolumns = 2, nrows = 3;
    
        int** test = (int**)malloc(nrows * sizeof(int*));
    	for(i = 0; i < 2; i++)
    		test[i] = (int*)malloc(ncolumns * sizeof(int));
    
    
        for(o = 0; o<=nrows-1; o++)
        {
            for( i=0;i<=ncolumns-1;i++)
            {
                test[o][i] = 1;
                cout << test[o][i];
            }
        }
    
        return 0;
    }
    What gives? I don't think it has anything to do with free() i put it on and made no difference
    My Ctrl+S addiction gets in the way when using Code Blocks...

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,452
    This is wrong:
    Code:
    for(i = 0; i < 2; i++)
        test[i] = (int*)malloc(ncolumns * sizeof(int));
    The magic number 2 should have been nrows.

    This is poor style:
    Code:
    for(o = 0; o<=nrows-1; o++)
    {
        for( i=0;i<=ncolumns-1;i++)
        {
            test[o][i] = 1;
            cout << test[o][i];
        }
    }
    I suggest:
    Code:
    for (int i = 0; i < nrows; ++i)
    {
        for (int j = 0; j < ncolumns; ++j)
        {
            test[i][j] = 1;
            cout << test[i][j];
        }
    }
    Using r and c instead of i and j respectively also makes sense, but more importantly, notice the use of < instead of <= when the array index starts from 0. Also, notice that I declared the variables near first use.

    Oh, and you really should free what you malloc.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,236
    Quote Originally Posted by oogabooga View Post
    There's a couple ways to do it. See the first couple of examples here.
    Ugh, that's an annoying FAQ entry:

    You can keep the array's contents contiguous, at the cost of making later reallocation of individual rows more difficult, with a bit of explicit pointer arithmetic:
    The implication is simply allocating a chunk of memory then indexing it is somehow less elegant than an array of pointers.. With some FUD about some mythical need to reallocate individual rows and the scary term "explicit pointer arithmetic."

    Allocating an array of pointers and then allocating the rows and managing all that just so you can have the [row][col] notation is just... totally pointless. Especially in C++ where you can easily abstract this away into a multi-dimensional iterator
    whiteflags likes this.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,452
    Quote Originally Posted by brewbuck
    The implication is simply allocating a chunk of memory then indexing it is somehow less elegant than an array of pointers.. With some FUD about some mythical need to reallocate individual rows and the scary term "explicit pointer arithmetic."
    I think you're reading FUD into a statement where there is none I don't see an implication that the method is less elegant. I think that needing to reallocate individual rows is a possibility that cannot always be dismissed (even if we're not talking about a "jagged" array of arrays), I don't see what's so scary about "explicit pointer arithmetic" compared to the scary "multi-dimensional iterator"

    What I don't like is that the statement points out a potential cost without pointing out the definite benefit of a fixed number of allocations, but maybe that benefit is just plain obvious.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem making strings in a malloc-ed struct
    By itsthemac in forum C Programming
    Replies: 6
    Last Post: 03-28-2011, 09:01 PM
  2. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  3. malloc 2D array
    By DerekC in forum C Programming
    Replies: 10
    Last Post: 03-02-2010, 07:55 AM
  4. Array for malloc needed
    By sarathius in forum C Programming
    Replies: 3
    Last Post: 03-10-2008, 12:33 PM
  5. Making an array with x and y
    By |Wiz| in forum C++ Programming
    Replies: 14
    Last Post: 03-06-2006, 08:15 PM

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