0

I am learning C++ and confused why a changes occurred in function gets reflected in main. Can anyone say how to change the array in function without reflecting in main module..

thx for the help

#include <iostream>
using namespace std;

void function1(int x[],int n){
    for(int i=0;i<n;[enter image description here](https://i.stack.imgur.com/G17A6.png)i++){
        x[i]=0;
    }
}

int main(){
    int n;
    cout<<"Enter the number of terms :";
    cin>>n;
    int a[n];
    for(int i=0;i<n;i++){
        cin >> a[i];
    }
    function1(a,n);
    //after calling a function
    //printing an array declared in main 
    for(int i=0;i<n;i++){
        cout<<a[i]<<endl;
    }
    return 0;
}

I wrote a code to check the changes of data in main and function module. After calling the function, i thought the data entered to the array before calling the function wouldn't be changed. However, changes in data in function, reflected in main module

  • 2
    The material from which you are learning should explain to you that an array type in a function parameter like `int x[]` in your example isn't actually an array, but a pointer, and that passing an array as a pointer means passing a pointer to the first element of the same array, without creating any new local array (array-to-pointer decay). It should also explain that `int a[n];` is not valid C++, since the size of an array must be a constant. Where are you learning C++ from? Follow one of the [recommended books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – user17732522 Mar 05 '23 at 03:39
  • 1
    "_Can anyone say how to change the array in function without reflecting in main module_": By not using C-style arrays. Use `std::vector` instead, which behaves as you expect. It should also be introduced early in any introduction to C++. – user17732522 Mar 05 '23 at 03:43
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 05 '23 at 03:54
  • 1
    Because you're making changes through a pointer to the elements of the array. – Jason Mar 05 '23 at 04:02

0 Answers0