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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.