Harimangal Pandey Harimangal Pandey -4 years ago 58
C++ Question

Minimizing the Memory Used

i got a doubt, as we know that Pointer is a variable that stores address.
Can i store a Value at that address using

cin>>(*p);


without using any other normal variable.
Code Below explains the same:

#include'iostream'
int main()
{
long long *p;
cin>>(*p);
cout<<(*p);
return 0;
}


Is it right to store variable like that?

If we could store value like this then we can save so much of memory, because we only pointer variable has to be assigned the memory. Which is far less than the size of Normal long long data type.

Answer Source

The pointer has an undefined value, hence any attempt to write at that address will result in undefined behavior.

Better:

int main()
{
    long long *p = new long long();  // heap allocation
    cin>>(*p);
    cout<<(*p);
    delete p;
    return 0;
}

OR

int main()
{
    long long p;  // stack variable
    cin>>p;
    cout<<p;
    return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download