Omar AbdelFattah
Omar AbdelFattah

Reputation: 31

C++: What is the difference between ' arr ' and ' arr[] '

A part of a program I am working on is to sort an array of ints, so I used the easiest algorithm for me, selection sort, to do so. When I checked the algorithm online I found that the argument of the function is selectionSort(int arr[], int n) where n is the size of the array, that will be inputted later on; so when I called the function in the main() function I called it as follows selectionSort(arr[n], n) and tried printing the array just to check that the function works and it didn't work - just printed the array without sorting. Then I just removed the squared brackets and it worked well.

Here is the code:

void swap(int *xp, int *yp){
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

void selectionSort(int arr[], int n){
    int i, j, min_idx;
    for (i = 0; i < n-1; i++)
    {
        min_idx = i;
        for (j = i+1; j < n; j++)
          if (arr[j] < arr[min_idx])
            min_idx = j;
        swap(&arr[min_idx], &arr[i]);
    }
}
int main(){
    int n; cin>>n;
    int arr[n];
    for(int i = 0; i < n; i++){
        cin>>arr[i];               //fill in the array
    }
    selectionSort(arr, n);         //Here is the point, if I write arr[]
    for(int i = 0; i < n; i++){cout<<arr[i];}
}

Selection Sort reference

The Problem I am working on on Code Forces

Upvotes: 2

Views: 2344

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

When you use arr in your function call, it will decay to a pointer to its first element, it's equal to &arr[0]. It will have the type int*.

If you use arr[i] (for any valid index i), then you pass the value of a single element of the array. It will have the type int.

Since the function expects a pointer (when declaring an argument, int arr[] is equal to int* arr), passing plain arr will work fine, but arr[i] will get a complaint from the compiler since you pass something of the wrong type. However depending on the type of the array, this complaint might be just a warning, and the compiler will pretend that the value is a pointer. This is wrong and will lead to undefined behavior (and probably crashes). The lesson for this: Don't ignore warning messages from the compiler, treat them as actual errors instead.

And if you write arr[] (without any index) when calling the function, then that's a syntax error.

Upvotes: 5

Related Questions