Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying one pointer to other in C++

Tags:

c++

pointers

#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?

like image 815
Raman Gupta Avatar asked Jul 27 '12 17:07

Raman Gupta


3 Answers

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 :)

like image 197
Luchian Grigore Avatar answered Oct 25 '22 06:10

Luchian Grigore


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;
}
like image 44
jahhaj Avatar answered Oct 25 '22 05:10

jahhaj


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

like image 20
A B Avatar answered Oct 25 '22 06:10

A B