caramel1995
caramel1995

Reputation: 3055

Create a pointer for constant memory location address??(C programming)

The Question

1.)Is it possible to declare a pointer variable to reference to the memory address of a constant??I've tried this before pt = &20;(**pt is a pointer variable) but it's not working , so does it mean we can't do it??By the way if it's possible how am i going to work it out??

Upvotes: 0

Views: 2110

Answers (3)

Jens Gustedt
Jens Gustedt

Reputation: 78963

No, literal constants as 20 are not objects and so they don't have addresses.

Different from that are const qualified variables as in Alex' answer. As all variables they refer to an object and so you may take their address. But beware that you then have to have the pointer also be to the const qualified type.

Upvotes: 0

Alexey Frunze
Alexey Frunze

Reputation: 62106

No. You must do this:

const int x = 20;
const int* p = &x;

Upvotes: 5

unexpectedvalue
unexpectedvalue

Reputation: 6139

Yes it is.

void * ptr = 0xdeadcode;

Don't do it.

Edit: Or you mean, address of a constant, not constant address? Like:

const int n = 123;
const int *ptr = &n;

Upvotes: 0

Related Questions