1

As we know that arrays are passed by pointers only in C then swap1(arr[i],arr[j]) below means that two pointers will be passed to the function swap1() then why swap1(arr[i],arr[j]) is giving me error? According to function prototype of swap1() two pointer should be passed and I am passing that.

On the other hand, when I am passing actually the address swap1(&arr[i],&arr[j]) it is working fine, which is obvious.

void swap1(int *a,int *b){
   int temp = *a;
   *a = *b;
   *b = temp;
}
void bubble(int arr[], int i, int n)
{
    for(int j=i+1;j<n;j++){
        if(arr[i]>arr[j])
        swap1(arr[i],arr[j]);
    }
}
1
  • Turn on all warnings and errors (-Wall -Wextra -Werror), this should not compile. Commented Feb 26, 2020 at 12:34

3 Answers 3

2

In the bubble function the variable arr is a pointer (type int *). That means arr[i] (for any i) is not a pointer, it's an int value.

When you pass those int values to swap the compiler should complain about it, and it's correct because the swap function expects pointers (again of type int *).

To get a pointer to arr[i] you need to use the address-of operator &, as in &arr[i]:

swap1(&arr[i], &arr[j]);
Sign up to request clarification or add additional context in comments.

Comments

0

when arr is an array, indeed passing arr is actually passing a pointer to the first element. however when you use the deference operator [i], you pass the value of the i-th element and not its address.

Comments

0

From the C Standard (6.5.2.1 Array subscripting)

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

So when you call the function like

swap1(arr[i],arr[j]);

you are passing the values of the two elements of the array. To pass pointers to these elements you could write

swap1( arr + i, arr + j );

The difference will be obvious if the first call to rewrite as it is written in the quote from the C Standard

swap1(arr[i],arr[j]);

is equivalent to

swap1( *( arr + i ), *( arr +j ) );

that is the pointers are dereferenced before passing the control to the function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.