2

In my code, I used pointer array like this.

arr = (int*)malloc(N * sizeof(int));

        for (i = 0; i < N; i++)
            scanf("%d", (arr + i));

Because pointer arithmetic points address.

But I wonder if it's right to only write (arr+i) without * or &.

What is right?

Please help me.

2
  • What you have is correct. The scanf arg needs to be an int * which is exactly what you have. Using * would be wrong as that would give an int and using & would be wrong as that would give an int **. Commented Sep 24, 2020 at 11:47
  • 1
    For any pointer or array a and index i, the expression *(a + i) is exactly equal to a[i]. From that follows that &a[i] is equal to &*(a + i) which is equal to a + i. Which is exactly what you have. Commented Sep 24, 2020 at 11:49

1 Answer 1

6

The expression arr + i has the type int * and is equivalent to the expression &arr[i] (or even to the expression &i[arr] :)).

So you may write either

scanf( "%d", &arr[i] );

or

scanf( "%d", arr + i );
Sign up to request clarification or add additional context in comments.

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.