0

Given the code below:

double** vr(new double*[nx]);  
vr[i]=new double[ny];
for(int i=0;i<nx;++i) { //Loop 200times
    for(int j=0;j<ny;++j) { //Loop 200times

        vr[i][j]=double(i*i*i*j*c1);

    }
}

For vr[i][j] = double(i * i * i * j * c1);

why is it not required to address the value using * for example *(vr[i][j]).

It is just an address isnt it?

3
  • This is pretty much answered here. Array indexing and pointer arithmetic are the same idea expressed in different syntax. Commented May 2, 2018 at 0:38
  • 1
    and your question is not initialization but assignment. Commented May 2, 2018 at 0:41
  • I just wanted to ask why does it dereference? Is there some kind of overloaded [] operator for a pointer class maybe? Commented May 2, 2018 at 1:08

4 Answers 4

1

vr[i][j] is a double not an address.

Basically, if p is of type T* then p[i] means *(p+i) and is of type T, where T can be any type.

In your case vr is double**, so vr[i] is double* and vr[i][j] is double.

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

2 Comments

I just wanted to ask why does it dereference?
Is there some kind of overloaded [] operator for a pointer class maybe?
1

When you do vr[i] you're already dereferencing because vr[i] is equivalent to *(vr + i). This means that vr[i][j] is double dereferencing, and is equivalent to *(*(vr + i) + j).

See pointer arithmetic for further information.

1 Comment

I just wanted to ask why does it dereference? Is there some kind of overloaded [] operator for a pointer class maybe?
1

From dcl.array/6

the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)) ([expr.sub]). Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2-th member of E1. Therefore, despite its asymmetric appearance, subscripting is a commutative operation.  — end note ]

Thus, operator[], the subscript operator, works the same as using operator* (unary) for indirection.

int a[5] = {1, 2, 3, 4, 5}; // array
int* pa = a;                // pointer to a
std::cout <<  pa[2];        // (ans. 3) using subscript operator
std::cout << *(pa + 2);     // (ans. 3) using indirection, accessing A's 3rd element

1 Comment

Do you think @NuPagadi should take notes? Thanks btw! :)
1

Subscript operator ([i]) does the dereferencing. It says to shift on i "cells" and get the object located there.

2 Comments

I just wanted to ask why does it dereference? Is there some kind of overloaded [] operator for a pointer class maybe?
@cLMaine It is the semantics. Why does + summarize? You used c-style pointers. They are not classes. But, for example, unique_ptr has overloaded [] operator.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.