-2
void sort(int *ptr, int n) {
    int i,j,tmp;
    for (i=0;i<n;i++)
        for (j=i;j<n;j++)
                if (ptr[i] > ptr[j])
                {
                    tmp=ptr[i];
                    ptr[i]=ptr[j];
                    ptr[j]=tmp;
                }
}

AND

void sort(int *ptr, int n) {
    int i,j,tmp;
    for (i=0;i<n;i++)
        for (j=i;j<n;j++)
                if (*(ptr+i) > *(ptr+j))
                {
                    tmp=*(ptr+i);
                    *(ptr + i) = *(ptr + j);
                    *(ptr + j)=tmp;
                }
}

It has the same output. Both works. I've seen people using both, although obviously the first one seems more natural and intuitive than the second. Is there any problems whatsoever in using the first one over the second? Also, what are the main differences between them, if any?

dbush
  • 205,898
  • 23
  • 218
  • 273
manubmxnsb
  • 151
  • 1
  • 14

2 Answers2

3

The two pieces of code are semantically equivalent.

Section 6.5.2.1p2 of the C standard regarding the array subscript operator [] states:

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 E 1is 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 for example ptr[i] is exactly the same as *(ptr+i), as well as other similar instances.

The first version of the code using array subscripting is generally preferred because it is more readable.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

Nothing. It's merely a matter of style.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76