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

4
  • 3
    @M.A haven't tested, but are you sure that doesn't just set the first one as 666 and the rest of the elements as 0? Commented Feb 17, 2021 at 8:44
  • @mediocrevegetable1 yep good catch :) Commented Feb 17, 2021 at 8:47
  • Don't fix the code in your question, it invalidates the posted answer. Commented Feb 17, 2021 at 8:53
  • 1
    BTW, int grid[m][n]; is a non-standard VLA. Commented Feb 17, 2021 at 9:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

for (int j = 0; j < n; i++) should be j++
@ΦXocę웃Пepeúpaツ Yes I've fixed it
Yea I fixed the code printing but it's still giving the same error also i tried this memset but still having the same problem memset(grid, 0, sizeof(int) mn);
Yea it works if tried memset(grid, 0, sizeof(int) mn);
@youssefmyh Do you realise that int grid[m][n] ; is not legal C++? In C++ array sizes must be constants, but m and n are variables.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.