Hi I am trying to call a 3rd party method which relies on const char* I want to pass an arbitrary value.

The (broken) code below should show what I'm trying to do.

#include <iostream>
#define MAX 1000
// 3rd party stuff
void ConstPtrMethod(const char* s) {
    std::cout << s << std::endl;
}

// My stuff:
int main() {
    const char* ConstBuffer;
    for (int i = 0; i < 10; i++) {
        char* buf;
        buf = ConstBuffer;
        sprintf(buf, "%d", i);
        ConstPtrMethod(ConstBuffer);
    }
}

I'm a cpp noob btw. What I want to know is why the line buf = Constbuffer does not work as well as a way around this if possible.

Thanks in advance.

You could use

buf = const_cast<char*>(ConstBuffer);

but using a cast to get your code to work is a good indicator of poorly written code.

Edited 5 Years Ago by gerard4143: n/a

When a function is taking in a "const char*", it is only saying that it will not modify the data pointed to by that pointer. It doesn't mean that you are not allowed to change the data. In other words, a non-const pointer can be implicitly cast to a const pointer, but not the other way around. If you have a const pointer, you cannot assign it to a non-const one, because the constness of the original pointer is like a "promise not to modify" (a promise the compiler "forces" you to keep), so casting to a non-const pointer would be breaking that promise. However, if you have a non-const pointer there is no promise attached to it, so you can easily pass it to a function that promises not to modify the data.

So, for your problem, the solution is really simple when you consider what I just said:

#include <iostream>
#define MAX 1000
// 3rd party stuff
void ConstPtrMethod(const char* s) {
    std::cout << s << std::endl;
}

// My stuff:
int main() {
    char* Buffer; //remove the const here.
    for (int i = 0; i < 10; i++) {
        sprintf(Buffer, "%d", i); //since Buffer is non-const it can be modified
        ConstPtrMethod(Buffer);   //Buffer can be directly cast to a const char*
    }
}

NOTE: You do understand that your simple example is not a working piece of code, right? You would need to allocate memory for Buffer to point somewhere before you do anything else! So this would be a working example:

#include <iostream>
#define MAX 1000
// 3rd party stuff
void ConstPtrMethod(const char* s) {
    std::cout << s << std::endl;
}

// My stuff:
int main() {
    char* Buffer = new char[MAX]; //remove the const here.
    for (int i = 0; i < 10; i++) {
        sprintf(Buffer, "%d", i); //since Buffer is non-const it can be modified
        ConstPtrMethod(Buffer);   //Buffer can be directly cast to a const char*
    }
    delete[] Buffer;
}
This question has already been answered. Start a new discussion instead.