Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to const and normal pointer can be mixed?

Tags:

c

Is the value of *b undefined when printf() is called?

void foo(int *a) {
  const int *b = a;
  int *c = a;
  *c = 2;
  printf("%d\n", *b); // what must be *b? 1, 2 or undefined?
}

int d = 1;
foo(&d);
like image 500
misianne Avatar asked May 03 '11 14:05

misianne


People also ask

Can be marked as a pointer to const?

The pointer argument '%argument%' for function '%function%' can be marked as a pointer to const (con. 3). A function with a T* argument has the potential to modify the value of the object. If that is not the intent of the function, it is better to make the pointer a const T* instead.

How do you declare a pointer to a constant in C++?

Pointers with Const Memory Address Pointers with a constant memory address are declared by including the const after the *. Because the address is const, the pointer must be assigned a value immediately.

Can you increment a const pointer?

A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.

Is a pointer whose value can not be changed after initialization?

A const pointer is a pointer whose address can not be changed after initialization.


1 Answers

It will print 2. const int *b literally means:

Pointer to an integer whose value cannot be altered through its dereferentiation.

This does not mean that the value the pointer points to may not change. In fact it's perfectly valid to change. A likely scenario to use this, are structures that keep a read only reference to some large structure. The reference may change, but the functions working with that structure may not change what's behind the pointer.

Imagine a driver or similar that hands out a read only memory mapping of whatever data the device delivered: The address of the mapping is not constant, but since this is a read only mapping the user program may not write to it. OTOH when the device updates the data the contents of the buffer will change, but not necessarily the mapping address.

like image 70
datenwolf Avatar answered Sep 17 '22 12:09

datenwolf