0

If you have a function that takes the pointer of an array, would there be any use in using pointers to each element in the array, or is it redundant? For example:

int sum(int(*arr)[3]) {
    int i,j, sum = 0;
    for (i =0; i < ROW ; i ++) {
        for (j =0; j < COL ; j ++) {
            sum = sum + *(*( arr +i )+j);
        }
    }
}

Would using arr[i][j] be the same in this case?

1 Answer 1

1

arr[i] is required by the standard to be equivalent to *(arr + i) so no, there is no point in not using arr[i] which is more readable.

Speeding up 2d array access is a complex topic. There are some techniques for performance improvement, but those take hardware architecture (e.g. cache) into account are are related to access patterns rather than access syntax.

Sign up to request clarification or add additional context in comments.

2 Comments

Correct, but would using *(arr+i) take up fewer resources? Or is the answer much more complicated as you noted?
@Ailany what resources? The answer is simple regarding the array index operator vs pointer dereference: it's 100% equivalent. It generates identical asm code as you can see here: godbolt.org/z/dYWz3bcof

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.