C++ programming. Can someone please explain to me whats happening here and inter
ID: 3854153 • Letter: C
Question
C++ programming.
Can someone please explain to me whats happening here and interpret it top down in laymans terms. Thank You
#include <iostream>
#include <string>
using namespace std;
int main () {
int i[][3] = {
{1, 2, 3},
{4, 5, 6}
};
int* pointy = &i[1][1];
int* copyPointy = pointy;
// [!] This is a pointer reference! i.e., refPointy
// is just another name for pointy
int*& refPointy = pointy;
*pointy = 100;
pointy = &i[0][2];
cout << *pointy << endl;
cout << *copyPointy << endl;
cout << *refPointy << endl;
}
Explanation / Answer
#include <iostream> //#include indiates what library files are required by the program
#include <string>
using namespace std;
int main () { //main is where execution begins
int i[][3] = { //2D array(you may consider this similar to matrix) is declared and initialized
{1, 2, 3}, //in C++ array indexing starts from 0,0
{4, 5, 6} // first row is 0th row and 1st col 0th col
}; //i[0][0] = 2 // i[0][1] = 2 //i[1][1] = 5 etc.
// in C and C++ pointer type variable are responsible for storing addresses of a particular data type
// an integer pointer can stre address of an integer variable
// & operator extracts the address of a variable, i.e. &a means address of a
int* pointy = &i[1][1]; //initer type pointer pointing to element 1,1
int* copyPointy = pointy; //another integer pointer
// [!] This is a pointer reference! i.e., refPointy
// is just another name for pointy
int*& refPointy = pointy; //this is a reference pointer
// a reference object is clone of the original object. Change in either of them will be reflected to the othe object
*pointy = 100; //*pointy refers to the variable stored at address location pointy. In this case *pointy = i[1][1] = 100
pointy = &i[0][2]; //pointy now points to i[0][2] = 3
cout << *pointy << endl; // as said pointy now points to i[0][2], and as we print *pointy, output is 3
cout << *copyPointy << endl; //copy pointy still points to i[1][1], and value stored at i[1][1] is 100, so 100 is printed
cout << *refPointy << endl; //same as pointy, refPointy points to i[0][2] containing 3
}
Clear enough?
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.