Question on Arrays

When you enter data into an array via prompt, will it overwrite the data within the array if u call the function again, eventhough u never close the program ?
If you have a variable, and you write a value to it, and then you write different data into the exact same variable, the original data is replaced with the new data.


1
2
3
4
5
6
7
8
9
10
#include <iostream>
int main()
{
  int x;
  std::cin >> x;  // user enters a value
  std::cout << x; // show the value the user entered

  std::cin >> x; // user enters a different value
  std::cout << x; // the value changed
}


I'm not sure I completely understand your question, but it sounds the same as Moschops describes. If you pass an array to a function that writes to it, then call the same function with the same array again, it will write over the data you previously input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using namespace std;

void i_array_in(int* i_arr)
{
	for (size_t i = 0; i != 3; ++i) cin >> i_arr[i];
}

void i_array_out(int* i_arr)
{
	for (size_t i = 0; i != 3; ++i) cout << i_arr[i] << ' ';
	cout << endl;
}

int main()
{
	int i_array[3];
	cout << "Enter three integers: ";
	i_array_in(i_array);
	i_array_out(i_array);
	cout << "Enter three DIFFERENT integers: ";
	i_array_in(i_array);
	i_array_out(i_array);

    return 0;
}


If you run that code with 1 2 3, then run it again with 4 5 6, you'll see that the program never closed, we passed the same array to our read in function twice, but it will write over our first three integers with three new integers.
Last edited on
Topic archived. No new replies allowed.