I have the following array: int arr[] = { 3,5,5,1,5 };
and I want to change the value of all the elements to 998
. How I do this is that I call two functions, one without the size
, and one with size.
I know size
can be determined by sizeof(arr)/sizeof(arr[0])
, but this does not work in one of my functions.
In the first function, I don't pass in the size, and C++ calculates it.
change_array(arr, 998); // expect arr to become {998, 998, 998, 998, 998}
cout << " arr[2] = " << arr[2] << endl;
calls:
void change_array(int arr [],int new_value)
{
int size = sizeof(arr) / sizeof(arr[0]); //I ran in debugger, but this doesn't work
for (int i = 0; i < size ; i++) {
arr[i] = new_value;
}
}
but this prints arr[2] = 5
.
When I pass in the size, like this:
change_array_size(arr, 5, 998);
cout << " arr[2] = " << arr[2] << endl;
then that calls:
void change_array_size(int arr[], int size, int new_value)
{
for (int i = 0; i < size; i++) {
arr[i] = new_value;
}
}
and in this one it actually changes the value: arr[2] = 998
.
Why? The sizeof
operator didn't seem to work in this case?