0

I want to fill a 2D array but it's not guaranteed to be filled entirely. Normally I would use a nested for loop, as follows:

for(i = 0; i < 10; i++)
{
  for(j = 0; j < 10; j++)
  {
    array[i][j] = 1;
  }
}

In this case I'm filling it entirely.

However, I don't know at first how many elements I have to put inside. I thought about a while with a sentinel value, but then I should put inside a control statement to make sure the value won't exceed the size of the array, is that correct?

The code I put here is just an example, I'm actually curious about a different way to fill arrays since I've always seen for or nested for and I was wondering if there are other ways to do it. Thanks in advance.

Wreigh
  • 3,215
  • 16
  • 37
Goner
  • 31
  • 1
  • 4
  • 1
    Refer the question https://stackoverflow.com/questions/17288859/using-memset-for-integer-array-in-c This might be useful for you. – yadhu Jul 08 '18 at 22:29
  • you do know the boundaries of your array and want to fill it completely, or just up to a certain point? – R.S. Jul 08 '18 at 22:30
  • 2
    I think you still need a `for` loop, you just need to limit the end condition of your loop based upon your known size. e.g. `for(I=0;i – LoztInSpace Jul 09 '18 at 01:41
  • @R.S. I know the dimension of the array at the beginning since it's static, but I want to know, in case I don't have to completely fill the array, what kind of command could I use instead of a for loop with a break? – Goner Jul 09 '18 at 11:38
  • @LoztInSpace that's an other way I thought too, but with `malloc` aren't you supposed to use a `for loop` anyway? – Goner Jul 09 '18 at 11:39
  • 1
    Iteration between values can be achieved in many ways. For, while, do, recursion etc. You just have to understand them and pick the best for your situation. I don't think I understand your question to be honest. Mostly in this case for would be appropriate and well understood by anyone reading the code – LoztInSpace Jul 09 '18 at 12:20

1 Answers1

-1

Store them in an 1D array first then you can transfer from 1D array to 2D array and in your nested forloop you can check whether there are elements in 1D array. Does this solves it?

manjy
  • 109
  • 1
  • 2
  • 12