somewho3
somewho3

Reputation: 11

C++ Pointer to Pointer

I want to have a pointer to a constant, and pass its address to a function that will increment it.

int f1(const int **ptr) {
    int n = **ptr; //use pointer
    (*ptr)++; //increment pointer
    return n;
}

void foo(const int *data) {
    const int *p = data;
    const int n = f1(&p); //error: invalid conversion from ‘const int**’ to ‘int**’
                          //error:   initializing argument 1 of ‘int LevelLoader::readWord(byte**)’


}

How do I declare the pointers?

Upvotes: 0

Views: 267

Answers (3)

René Richter
René Richter

Reputation: 3909

Try

int f1(const int *& ptr) {
  int n = *ptr;
  ++ptr; 
  return n;
}

void foo(const int *data) {
  const int *p = data;
  const int n = f1(p); 
}

instead.

The error message indicates that LevelLoader::readWord doesn't take a const byte**.

Upvotes: 2

richb
richb

Reputation: 4906

Check again, this code is correct. It shouldn't generate the errors you claim.

EDIT: You fixed the void problem so answer amended accordingly.

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 473352

This:

const int *data;

is a pointer to a constant integer. That means that you are not allowed to change the data pointed to by data. You can read and copy the data, but you can't do:

(*data) = 5;

That's illegal in C++ because it was declared const int *.

If you take the address of a const int *, you get a const int **, which is a pointer to a pointer to a constant integer. So you still cannot change the integer. Any attempt to do so will cause the compiler to complain.

If you want to be able to change the integer, then foo and f1 should not take const int * values. They should take int * values.


I don't want to modify the constant. I want to modify the pointer to it (p in foo())

So, you're given a pointer. And you want to increment the pointer. So just do so:

void foo(const int *data) {
    const int *p = data;
    data++;
}

You have incremented the pointer. This will not affect the caller to foo, as the pointer itself is copied by value.

Upvotes: 1

Related Questions