0

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?

9
  • 1
    anything other than C C++ java? Feb 16, 2017 at 12:58
  • ... Why the Java tag!?
    – Borgleader
    Feb 16, 2017 at 12:58
  • Java is not needed , it's just C++
    – VD18421
    Feb 16, 2017 at 12:58
  • I took it out I added by accident cause it was in suggested.
    – VD18421
    Feb 16, 2017 at 12:59
  • then remove it. you have an edit button Feb 16, 2017 at 12:59

0

Browse other questions tagged or ask your own question.