0

I am trying to find the best way to fill 2D Array with a specific value. Is there any better way to loop the 2D Array? I tried memset doesn't work I tried std::fill but I doubt there is something wrong with my code.

void fillMultipleArray(int m, int n, int value)
{
    int grid[m][n];
    
    memset(grid, 0, sizeof(grid));
    
    
    for (int i = 0; i < m; i++) {
        
        for (int i = 0; i < n; i++) {
            
            std::cout << grid[m][n] << std::endl;
        }
    }    
}

Output

-272632896 -272632896 -272632896 -272632896 -272632896 -272632896 -272632896 -272632896

Thanks in advance

Jarod42
  • 203,559
  • 14
  • 181
  • 302
ymyh
  • 11
  • 6

1 Answers1

1

Using memset is fine, instead look carefully at your printing code, it has multiple mistakes

for (int i = 0; i< m; i++) {
    for (int i = 0; i< n; i++) {
        std::cout<< grid[m][n]<< std::endl;
    }
}

That should be

for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
        std::cout<< grid[i][j] << std::endl;
    }
}

It's a good lesson, when the output is wrong, it could be because your calculation is wrong, but it could just as easily be that you are printing your results wrong. Try not to make too many assumptions.

john
  • 85,011
  • 4
  • 57
  • 81