Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Four methods to create, pass to function and delete 2d arrays in c++

Four methods to create, pass to function and delete 2d arrays in c++

Scheduled Pinned Locked Moved C / C++ / MFC
c++data-structuresperformancequestion
6 Posts 3 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    Javier Luis Lopez
    wrote on last edited by
    #1

    Is the first method correct for all the platforms? I describe the three methods in the following code:

    //Shows 4 different ways to create, pass to functions and delete 2d-arrays
    #include
    #include
    using namespace std;//#include
    //std::swap(matriz1m, matriz2m); //The best way but VC11 only!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    #define YMAX 6
    #define XMAX 4

    void print_data2d(float *matriz[XMAX],int max1,char *method);
    void print_data2d(float (*matriz)[XMAX],int max1,char *method);

    void print_adress(float (*matriz)[XMAX],int ymax,char *method);
    void print_adress(float *matriz[XMAX],int ymax,char *method);

    //This print method only works for method 1 & 2:
    void print_data2d(float *matriz,int ymax,int xmax,char *method);
    //This print method only works for method 3 & 4:
    void print_data2d(float **matriz,int ymax,int xmax,char *method);

    int main()
    {
    int x,y;

    //The three methods to create the arrays:
    
    //1. First method: one-step "new" and one-step adress assign:
    //1.1. Buffer memory reservation:
    float \*matriz1\_m=new float\[XMAX\*YMAX\];//Buffer
    //1.2. Address assign:
    float (\*matriz1)\[XMAX\]=(float (\*)\[XMAX\]) &matriz1\_m\[0\];//Assign
    
    
    //2. Second method: No buffer needed. Only one-step "new" and one-step adress assign:
    float (\*matriz2)\[XMAX\]=new float\[YMAX\]\[XMAX\];//array definition   \[XMAX\], caution!!
    
    //3. Another method: by using for loop for "new" and adress assign:
    //3.1. Array declaration:
    float \*matriz3\[YMAX\];   // \[YMAX\] caution!!
    //3.2. Address assign:
    for (y=0;y
    
    B L 2 Replies Last reply
    0
    • J Javier Luis Lopez

      Is the first method correct for all the platforms? I describe the three methods in the following code:

      //Shows 4 different ways to create, pass to functions and delete 2d-arrays
      #include
      #include
      using namespace std;//#include
      //std::swap(matriz1m, matriz2m); //The best way but VC11 only!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

      #define YMAX 6
      #define XMAX 4

      void print_data2d(float *matriz[XMAX],int max1,char *method);
      void print_data2d(float (*matriz)[XMAX],int max1,char *method);

      void print_adress(float (*matriz)[XMAX],int ymax,char *method);
      void print_adress(float *matriz[XMAX],int ymax,char *method);

      //This print method only works for method 1 & 2:
      void print_data2d(float *matriz,int ymax,int xmax,char *method);
      //This print method only works for method 3 & 4:
      void print_data2d(float **matriz,int ymax,int xmax,char *method);

      int main()
      {
      int x,y;

      //The three methods to create the arrays:
      
      //1. First method: one-step "new" and one-step adress assign:
      //1.1. Buffer memory reservation:
      float \*matriz1\_m=new float\[XMAX\*YMAX\];//Buffer
      //1.2. Address assign:
      float (\*matriz1)\[XMAX\]=(float (\*)\[XMAX\]) &matriz1\_m\[0\];//Assign
      
      
      //2. Second method: No buffer needed. Only one-step "new" and one-step adress assign:
      float (\*matriz2)\[XMAX\]=new float\[YMAX\]\[XMAX\];//array definition   \[XMAX\], caution!!
      
      //3. Another method: by using for loop for "new" and adress assign:
      //3.1. Array declaration:
      float \*matriz3\[YMAX\];   // \[YMAX\] caution!!
      //3.2. Address assign:
      for (y=0;y
      
      B Offline
      B Offline
      Bram van Kampen
      wrote on last edited by
      #2

      Hi, Four Questions: 1st: What do you mean by 'Different Platforms' It's all standard CPP, Standard Libraries, etc. Should work on any machine that supports a CPP Compiler to ISO Standards. 2nd: Does it Work! (I Don't see any obvious errors at a Glance, but a First Glance can be deceiving in this game, which is the reason we do debugging. I am not willing to do that for you, but I'll offer Help if you encounter a Difficulty.) 3rd: What are you trying to prove, apart from that there is more than one way to skin a Cat (or in this case, write a piece of Code) Otherwise, Did you provide a Crude Example of a Bigger Problem, but you are trying to touch the basics, by simplifying the problem, (and sometimes by Abstracting the problem, hiding the real issues that you try to discuss). For Instance, did you abstract the concept of MFC Classes down to Floating Point Variables. 4th: If it all works, Why pose the question in the first place. (In other words, What was the real question!) Kind Regards :)

      Bram van Kampen

      J 1 Reply Last reply
      0
      • J Javier Luis Lopez

        Is the first method correct for all the platforms? I describe the three methods in the following code:

        //Shows 4 different ways to create, pass to functions and delete 2d-arrays
        #include
        #include
        using namespace std;//#include
        //std::swap(matriz1m, matriz2m); //The best way but VC11 only!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        #define YMAX 6
        #define XMAX 4

        void print_data2d(float *matriz[XMAX],int max1,char *method);
        void print_data2d(float (*matriz)[XMAX],int max1,char *method);

        void print_adress(float (*matriz)[XMAX],int ymax,char *method);
        void print_adress(float *matriz[XMAX],int ymax,char *method);

        //This print method only works for method 1 & 2:
        void print_data2d(float *matriz,int ymax,int xmax,char *method);
        //This print method only works for method 3 & 4:
        void print_data2d(float **matriz,int ymax,int xmax,char *method);

        int main()
        {
        int x,y;

        //The three methods to create the arrays:
        
        //1. First method: one-step "new" and one-step adress assign:
        //1.1. Buffer memory reservation:
        float \*matriz1\_m=new float\[XMAX\*YMAX\];//Buffer
        //1.2. Address assign:
        float (\*matriz1)\[XMAX\]=(float (\*)\[XMAX\]) &matriz1\_m\[0\];//Assign
        
        
        //2. Second method: No buffer needed. Only one-step "new" and one-step adress assign:
        float (\*matriz2)\[XMAX\]=new float\[YMAX\]\[XMAX\];//array definition   \[XMAX\], caution!!
        
        //3. Another method: by using for loop for "new" and adress assign:
        //3.1. Array declaration:
        float \*matriz3\[YMAX\];   // \[YMAX\] caution!!
        //3.2. Address assign:
        for (y=0;y
        
        L Offline
        L Offline
        leon de boer
        wrote on last edited by
        #3

        You seem to have yourself very confused on pointer dereferencing and memory allocation. You are trying to assign "right way" to something that has nothing to do with the language but what is essentially about memory ownership. Your version 3 is mongrel of a thing and NOT CLASSICAL AT ALL. Look carefully at what it is which is an array of pointers on the stack if within a function or on the heap if globally assigned and into which you place allocated memory. YUCK writing any function via pointer reference to access that abomination would be fun and dangerous it's not necessarily a persistent structure unless defined globally. So how about I give you 4 WHICH IS ACTUALLY THE CLASSICAL VERSION

        //4. The ACTUAL CLASSICAL METHOD
        //4.1. Create and Array of pointers:
        float \*\*matriz3 = new (float\*\[YMAX\]);   // Create an array of pointers
        //4.2. Fill each pointer in the array with a allocated pointer to a block of memory:
        for (int y = 0; y < YMAX; y++)
        	matriz3\[y\] = new float\[XMAX\];; 
        

        // Its derived from the standard C version which looks like this
        float **matriz3 = (float**)malloc(YMAX * sizeof(float*)); // Create an array of pointers to a float
        for (int y = 0; y < YMAX; y++)
        *matriz3[y] = (float*)malloc(XMAX *sizeof(float)); // Fill each pointer array entry

        So now you have another one and all of them are perfectly fine within the contexts of what they were designed to do although 3 is of very limited use locally. You would need to take care passing a reference to your version 3. Method 4 is usable anywhere and someone needs to take responsibility to delete/free the allocated memory blocks. Whats different is 1 and I think 2 allocate all the memory together in one big contiguous block, 3 & 4 don't do that they have a pointer block which points to memory blocks for each row array and those blocks can be all over the place in physical memory. Structurally they are both 2D float arrays but there is differences in there internal memory layout. Versions 3 & 4 will never produce anything that looks like version 1 without a lot of luck with memory allocation. I won't comment on 2 because I have a feeling it may be compiler dependent C++11 seems to say it will be a contiguous block but I am not sure all compilers will do it if they are not C++11 compliant. The two structures also do no use the same amount of memory take a 2x2 matrix. Version 1 simply allocates memory for 4 floats. Version 3 & 4 allocate 2 pointers and then 2 floats allocated into each pointer. So if your float

        J 1 Reply Last reply
        0
        • B Bram van Kampen

          Hi, Four Questions: 1st: What do you mean by 'Different Platforms' It's all standard CPP, Standard Libraries, etc. Should work on any machine that supports a CPP Compiler to ISO Standards. 2nd: Does it Work! (I Don't see any obvious errors at a Glance, but a First Glance can be deceiving in this game, which is the reason we do debugging. I am not willing to do that for you, but I'll offer Help if you encounter a Difficulty.) 3rd: What are you trying to prove, apart from that there is more than one way to skin a Cat (or in this case, write a piece of Code) Otherwise, Did you provide a Crude Example of a Bigger Problem, but you are trying to touch the basics, by simplifying the problem, (and sometimes by Abstracting the problem, hiding the real issues that you try to discuss). For Instance, did you abstract the concept of MFC Classes down to Floating Point Variables. 4th: If it all works, Why pose the question in the first place. (In other words, What was the real question!) Kind Regards :)

          Bram van Kampen

          J Offline
          J Offline
          Javier Luis Lopez
          wrote on last edited by
          #4

          You are right, the second method of course works and is my preferred method as long as I do not need a loop to create and delete it, but I have to be careful when sending the array to a function. Thank you to advise that the first one fits with iso standard.

          1 Reply Last reply
          0
          • L leon de boer

            You seem to have yourself very confused on pointer dereferencing and memory allocation. You are trying to assign "right way" to something that has nothing to do with the language but what is essentially about memory ownership. Your version 3 is mongrel of a thing and NOT CLASSICAL AT ALL. Look carefully at what it is which is an array of pointers on the stack if within a function or on the heap if globally assigned and into which you place allocated memory. YUCK writing any function via pointer reference to access that abomination would be fun and dangerous it's not necessarily a persistent structure unless defined globally. So how about I give you 4 WHICH IS ACTUALLY THE CLASSICAL VERSION

            //4. The ACTUAL CLASSICAL METHOD
            //4.1. Create and Array of pointers:
            float \*\*matriz3 = new (float\*\[YMAX\]);   // Create an array of pointers
            //4.2. Fill each pointer in the array with a allocated pointer to a block of memory:
            for (int y = 0; y < YMAX; y++)
            	matriz3\[y\] = new float\[XMAX\];; 
            

            // Its derived from the standard C version which looks like this
            float **matriz3 = (float**)malloc(YMAX * sizeof(float*)); // Create an array of pointers to a float
            for (int y = 0; y < YMAX; y++)
            *matriz3[y] = (float*)malloc(XMAX *sizeof(float)); // Fill each pointer array entry

            So now you have another one and all of them are perfectly fine within the contexts of what they were designed to do although 3 is of very limited use locally. You would need to take care passing a reference to your version 3. Method 4 is usable anywhere and someone needs to take responsibility to delete/free the allocated memory blocks. Whats different is 1 and I think 2 allocate all the memory together in one big contiguous block, 3 & 4 don't do that they have a pointer block which points to memory blocks for each row array and those blocks can be all over the place in physical memory. Structurally they are both 2D float arrays but there is differences in there internal memory layout. Versions 3 & 4 will never produce anything that looks like version 1 without a lot of luck with memory allocation. I won't comment on 2 because I have a feeling it may be compiler dependent C++11 seems to say it will be a contiguous block but I am not sure all compilers will do it if they are not C++11 compliant. The two structures also do no use the same amount of memory take a 2x2 matrix. Version 1 simply allocates memory for 4 floats. Version 3 & 4 allocate 2 pointers and then 2 floats allocated into each pointer. So if your float

            J Offline
            J Offline
            Javier Luis Lopez
            wrote on last edited by
            #5

            Thank you leon de boer, I included the 4th method and modified the comment at printf_data2d, I will check the last part of the post.

            L 1 Reply Last reply
            0
            • J Javier Luis Lopez

              Thank you leon de boer, I included the 4th method and modified the comment at printf_data2d, I will check the last part of the post.

              L Offline
              L Offline
              leon de boer
              wrote on last edited by
              #6

              Can I point out that if you really want portability with C++11, we do this and there is nothing your code can do with this as it uses the standard vector library

              #include using namespace std;

              #define YMAX 6
              #define XMAX 4

              // single line to define a 2D array of floats
              vector> matrix1(YMAX, vector(XMAX));

              // Now you can just set values
              matrix1[0][0] = 3.6f;
              matrix1[1][2] = 4.0f;
              matrix1[5][3] = 8.0f;

              // Or read them back
              float f = matrix1[1][2];

              The really cute part is it can be used on any standard type

              // single line to define a 2D array of STRINGS
              vector> stringmatrix(YMAX, vector(XMAX));

              // writing strings in the array
              stringmatrix[0][0] = "hello at 0,0";
              stringmatrix[1][2] = "this one";
              stringmatrix[5][3] = "hello at 5,3";

              // Getting string value from the array
              string whatdidwesay = stringmatrix[1][2];

              In vino veritas

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups