Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Return a 2d array from a function

Return a 2d array from a function

August 19, 2021 by James Palmer

This code returns a 2d array.
#include

// Returns a pointer to a newly created 2d array the array2D has size [height x width]

int** create2DArray(unsigned height, unsigned width)
{
int** array2D = 0;
array2D = new int*[height];

for (int h = 0; h < height; h++) { array2D[h] = new int[width]; for (int w = 0; w < width; w++) { // fill in some initial values // (filling in zeros would be more logic, but this is just for the example) array2D[h][w] = w + width * h; } } return array2D; } int main() { printf("Creating a 2D array2Dn"); printf("n"); int height = 15; int width = 10; int** my2DArray = create2DArray(height, width); printf("Array sized [%i,%i] created.nn", height, width); // print contents of the array2D printf("Array contents: n"); for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { printf("%i,", my2DArray[h][w]); } printf("n"); } // important: clean up memory printf("n"); printf("Cleaning up memory...n"); for (int h = 0; h < height; h++) // loop variable wasn't declared { delete [] my2DArray[h]; } delete [] my2DArray; my2DArray = 0; printf("Ready.n"); return 0; } A better alternative to using pointers to pointers is to use std::vector. That takes care of the details of memory allocation and deallocation. std::vector> create2DArray(unsigned height, unsigned width)
{
return std::vector>(height, std::vector(width, 0));
}

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in