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?

Joseph D.
  • 11,804
  • 3
  • 34
  • 67
cL Maine
  • 77
  • 7
  • This is pretty much answered [here](https://stackoverflow.com/questions/4955198/what-does-dereferencing-a-pointer-mean/4955297#4955297). Array indexing and pointer arithmetic are the same idea expressed in different syntax. – bnaecker May 02 '18 at 00:38
  • 1
    and your question is not initialization but assignment. – Joseph D. May 02 '18 at 00:41
  • I just wanted to ask why does it dereference? Is there some kind of overloaded [] operator for a pointer class maybe? – cL Maine May 02 '18 at 01:08

4 Answers4

1

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

iBug
  • 35,554
  • 7
  • 89
  • 134
NuPagadi
  • 1,410
  • 1
  • 11
  • 31
  • I just wanted to ask why does it dereference? Is there some kind of overloaded [] operator for a pointer class maybe? – cL Maine May 02 '18 at 01:07
  • 1
    @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. – NuPagadi May 02 '18 at 01:12
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
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
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.

xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30
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.

Daniele Cappuccio
  • 1,952
  • 2
  • 16
  • 31
  • I just wanted to ask why does it dereference? Is there some kind of overloaded [] operator for a pointer class maybe? – cL Maine May 02 '18 at 01:07