aa121
aa121

Reputation: 11

Getting pointer issue in C program

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]);
    }
}

Upvotes: 1

Views: 61

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

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.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409384

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]);

Upvotes: 2

nivpeled
nivpeled

Reputation: 1838

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.

Upvotes: 0

Related Questions