C/C++ Pointer Puzzle?


A Pointer is a variable that stores the address of another variable. The data type of the pointer is the same as the data type as the variable.

In this puzzle you need to know the size of the pointer that is being used. The puzzle checks our understanding of pointers by asking you the size of variable.

The size of int is 4 bytes, whereas the size of int pointer is 8. Now, let’s test your skills with the following exercise in c++ programming language.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a = 6 ;
   int *p = &a;
   int arr[5][8][3];
   int *q = &arr[0][0][0];
   int ans;
   cout<<"the value of a is "<<a<<endl;
   cout<<"predict the size of a ";
   cin>> ans;
   if(ans == sizeof(p)) {
      cout<<"Hurry! your prediction is right";
   } else {
      cout<<"Your Guess is wrong ";
   }
   cout<<"Now try this "<<endl;
   cout<<"arr is a 3D array"<<endl;
   cout<<"predict the size of arr ";
   cin>> ans;
   if(ans == sizeof(q)) {
      cout<<"Hurry! your prediction is right";
   } else {
      cout<<"Your Guess is wrong ";
   }
   return 0;
}

Output

the value of a is 6
predict the size of a 8
Hurry! your prediction is right
Now try this
arr is a 3D array
predict the size of arr 4
Your guess is wrong

Updated on: 07-Oct-2019

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements