Home > front end >  why do I have to use int &n instead of int n as parameter?
why do I have to use int &n instead of int n as parameter?

Time:01-04

I have to define a function to delete an element in an array, here is the code

void delete_element(int a[], int n, int pos)
{
    if (pos>=n)
    pos=n-1;
    else if (pos<0)
    pos=0;
    for (int i=pos-1;i<n-1;i  )
    {
        a[i]=a[i 1];
    }
    --n;
}

and here is an example:

int n;
printf("Enter the length of the array: ");
scanf("%d", &n);
int A[n]
for (int i=0;i<n;i  )
scanf("%d", &A[i]);
delete_element(A,n,2);

suppose that n=5 and A = {1,2,3,4,5}, after running the above code, it will print out {1,3,4,5,5}

When I use int n as parameter, the function deletes the element I want but the last element will appear twice in the array. I searched and then found out that by using int &n, the problem will be solved but I don't understand the reasons here. I would really appreciate if you could help me with this!

CodePudding user response:

If you use void delete_element(int a[], int n, int pos), the arguments are copied to the function. So if you decrease n by using --n;, it will only affect the "local" n, the copy.

If you use void delete_element(int a[], int& n, int pos), the parameter n is padded by referece. This means, there is no local copy used in the function but the variable n from the "outside world".
Therefore, --n; will now affect the variable which is given as a parameter to your function. You could create the same behavior by passing a pointer to the variable. In that case, the address is copied, but instead of the copied address the memory location it points to, the original variable, will be modified.

See e.g. https://www.geeksforgeeks.org/passing-by-pointer-vs-passing-by-reference-in-c/

CodePudding user response:

  1. This function doesn't delete an element in an array actually, because it just overlaps the data at pos with the next data, and the size is not changed.
  2. It seems that n is array's size, so when you use int n, the size is passed as value, so outer n is not changed. And when you use int& n, the size is passed as reference, so n will be changed.
  3. If you want to delete an element in array actually, you may refer to pop_back() or pop_front() function of vector.
  •  Tags:  
  • Related