I need help. Can someone explain to me a few lines of my teacher's code?

Hello guys I'm a beginner in C++ and I would like to ask for some help.
Can someone explain to me the meaning of the lines 4 and 5. Also I would really appreciate if someone explain to me the meaning of "new double [2]"I'm familiar with the "delete and new"operators but I can't understand the meaning of the number 2 in the brackets. And last but not least what does *(*(s-1)-2)= 65 mean ?
1
2
3
4
5
6
7
8
9
 int main(){
    double v[]={-37,280,-.45}, y=-17;
    double *x[]={v+2,&y,new double[2]}; // what is the meaning of the number 2
    x[2][0]=123; // what is the meaning of this ?
    x[2][1]=4; // what is the meaning of this ?
    double **g=x+1, ***s=&g, **z=new double*;
    *z=&y;
    cout<<"v[0] == "<<v[0]<<endl; 
    *(*(*s-1)-2)=65; // <---- what is the meaning of this ? 
Last edited on
Can someone explain to me the meaning of the lines 4 and 5.

Lines 4 and 5 are accessing elements of a 2-dimensional array.

I would really appreciate if someone explain to me the meaning of "new double [2]

That's allocating an array of two doubles.

what does *(*(s-1)-2)= 65 mean


In this context, * is the operator for de-referencing a pointer. So that's a complicated expression doing pointer de-referencing and pointer arithmetic to set the value of an element in the array that is pointed to by s.

Work through what s and g are pointing to, and what is being dereferenced in each part of the expression, and you should be able to figure it out.
your teacher is a maniac

*x[] is a array of double pointers
new double[2] creates a pointer to a double array with two elements

x[2][0] is the third element(note that they start from 0 to n-1) of the array of pointers, which is a pointer to a double array, so x[2][0] means that u are accesing the first element of the third element of the x[]

x[2][1] same, you are accesing the second element of the third element from x[]


***s is a pointer of a pointer of a pointer, ***s=&g initialises a triple pointer which points to a double pointer(**g), meaning that s points to g , where g points to the second element of the x[] array, which is a reference to the y variable(-17)

*(*(*s-1)-2)=65; lets take it from inside out *s-1 is equal to *(**g) - 1 which is (x + 1) - 1 thats x, x is equal to x[0] which is v+2 , v+2 is the third element of v[] which is -0.45, now now you have *(v + 2 - 2) which is v[0] which is -37 , now you change the -37 with 65 with assigment operator.

hope you understood

Thank you guys so much! And g3n0m3, yea he is a maniac :D
your teacher is a maniac

Or he's trying to test to what extent his students have understood the concepts he's teaching. Crazy, right?
Topic archived. No new replies allowed.