greatj0b greatj0b - 24 days ago 7
C++ Question

Function changing a variable, even when passed by value?

This is what I have, and it's causing some extremely weird discrepancies.

#include<iostream>
using namespace std;

void input_data(int data[], short size);

int main(){
short size;
int data[1000];

cout << "How many values would you like to store? ";
cin >> size;

while (size > 0){
cout << "Enter your " << size << " values:" << endl;
input_data(&data[1000], size);
cout << size << " values stored in array." << endl;
}
}

void input_data(int data[], short size)
{
int i;
for (i=0;i<size;i++){
cin >> data[i];
}
}


So this code should be pretty straight forward, but any time I enter a value other than 3 for
size
, the line
cout << size << " values stored in array." << endl;
ends up saying "0 values stored in array."

I don't understand how
input_data
could be changing the value of
size
, since I am passing by value, not by reference.

Why is this happening, and better yet, why is it working with the number 3?

Answer

You are overwriting the stack.

First you declare a function that takes an array:

void input_data(int data[], short size);

And then you call it. Instead of passing a pointer to an actual array like this:

input_data(data, size);

You are passing a pointer to the space immediately AFTER the array (which includes many things including size):

input_data(&data[1000], size);

While a parameter of data and &data[0] are essentially the same, &data[1000] points to a completely different thing - it points to the address of data[1000] which doesn't exist in the array because the array only has 1000 elements (from 0 to 999)