Home > Back-end >  C filling in array with input from another
C filling in array with input from another

Time:09-12

I'm just taking input for two arrays and manipulating the information. When I take input for both arrays it puts the information from the second into both arrays. In the code below I haven even commented out the input for the second array to see what happens and it still puts the input for M into both arrays. Can anyone see the cause?

int M[0], N[0];

std::cin >> m >> n;

  
  for (int i = 0; i < m;   i)
    {
      std::cin >> M[i];
    }

 for(int i=0; i<m; i  )
    {
      std::cout << M[i];
    }
  
  std::cout << "\n";
  
  for(int i=0; i<n; i  )
    {
      std::cout << N[i];
    }

CodePudding user response:

For starters these declarations

int M[0], N[0];

are invalid, You may not declare an array with zero elements.

Thus the code has undefined behavior.

Secondly variable length arrays are not a standard C feature. Either declare the arrays with the potentially maximum number of elements or use the standard container std::vector.

CodePudding user response:

the code that you just showed has a problem. You print only M because you didn't do the input for-loop for the N array. So the array N has nothing inside. So to fix this do another for and ask for input in the array N.

for (int i = 0; i < m;   i)
{
  std::cin >> N[i];
}

Hope this helps.

  • Related