Raman Gupta
Raman Gupta

Reputation: 169

copying one pointer to other in C++

#include <iostream>

using namespace std;

int main(int argc, char **argv) {
    int a=5;
    int *p,*q;

    *p = a;
    *q = *p;  //line 6

    cout<<*p<<p<<*q<<q;

    return 0;
}

This program hangs. It seems the problem is on line 6. Why is that?

Upvotes: 9

Views: 43072

Answers (4)

Luchian Grigore
Luchian Grigore

Reputation: 258688

Yes, those are dangling pointers and you're running into undefined behaviour.

You can't dereference a pointer that points to memory you don't own:

int* p;
*p; //illegal

int* x = NULL;
*x; //illegal

int* y = new int;
*y; //OK!

A correct version would be:

int main(int argc, char **argv) {
    int a=5;
    int *p = new int; 
    int *q = new int;

    *p = a;
    *q = *p;  //line 6

    cout<<*p<<p<<*q<<q;

    delete p; 
    delete q;

    return 0;
}

or

int main(int argc, char **argv) {
    int a=5;
    int *p;
    int *q;

    p = &a;
    q = p;  //line 6

    cout<<*p<<p<<*q<<q;

    return 0;
}

An even more correct version:

int main(int argc, char **argv) {
    int a=5;
    int p,q;

    p = a;
    q = p;  //line 6

    cout<<p<<p<<q<<q;

    return 0;
}

No pointers :)

Upvotes: 10

Maverick
Maverick

Reputation: 101

Two pointers can be copied using another variable as follows

#include<iostream>
using namespace std;


int main()
{
int *p,*q;
int a = 5;
p = &a;
q = &(*p);
a = 10;
std::cout<<*p<<std::endl;
std::cout<<*q<<std::endl;
}

However in this above example the address pointed by both the pointers is not the same. This will make both the pointers be determined by variable a In C++ another good way to do this would be using references

int a = 5;
int& p = a;
int& q = p;
std::cout<<p<<std::endl;
std::cout<<q<<std::endl;
std::cout<<&p<<std::endl;
std::cout<<&q<<std::endl;

Result:
5
5
0xbf9e7498
0xbf9e7498

Upvotes: 0

A B
A B

Reputation: 4158

The code you have assumes there is something stored at p when there is not.

Is this what you were trying to do?

int a=5;
int *p,*q;

p = &a;
q = p;  //line 6

cout<<(*p)<<p<<(*q)<<q;

In the code above, at the end of the program, p and q point to the same address - the address of where the integer a is stored

Upvotes: 2

jahhaj
jahhaj

Reputation: 3119

There's a problem in line 5 too. You have declared pointers but you haven't made them point at anything, that doesn't happen automatically. And dereferencing an uninitialized pointer, as you do, is liable to crash your program.

Something like this would be better.

int main(int argc, char **argv) {
    int a=5;
    int b, c;
    int *p,*q;

    p = &b; // make p point at b
    q = &c; // make q point at c
    *p = a;
    *q = *p;  //line 6

    cout<<*p<<p<<*q<<q;

    return 0;
}

Upvotes: 5

Related Questions