Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy const char*

Tags:

c++

string

char

I'm receiving a c-string as a parameter from a function, but the argument I receive is going to be destroyed later. So I want to make a copy of it.

Here's what I mean:

class MyClass
{
private:
 const char *filename;

public:
 void func (const char *_filename);
}

void MyClass::func (const char *_filename)
{
 filename = _filename; //This isn't going to work
}

What I want to achieve is not simply assign one memory address to another but to copy contents. I want to have filename as "const char*" and not as "char*".

I tried to use strcpy but it requires the destination string to be non-const.

Is there a way around? Something without using const_cast on filename?

Thanks.

like image 498
Ilya Suzdalnitski Avatar asked Feb 18 '10 10:02

Ilya Suzdalnitski


People also ask

Can const char * be reassigned?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.

What is const char * str?

The const char *Str tells the compiler that the DATA the pointer points too is const . This means, Str can be changed within Func, but *Str cannot. As a copy of the pointer is passed to Func, any changes made to Str are not seen by main....

What is the difference between const char * and char * const?

The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).

What does const char mean in Arduino?

char* is a mutable pointer to a mutable character/string. const char* is a mutable pointer to an immutable character/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so.


1 Answers

Use a std::string to copy the value, since you are already using C++. If you need a const char* from that, use c_str().

class MyClass
{
private:
    std::string filename;
public:
    void setFilename(const char *source)
    {
        filename = std::string(source);
    }

    const char *getRawFileName() const
    {
        return filename.c_str();
    }
}
like image 88
Pontus Gagge Avatar answered Oct 05 '22 00:10

Pontus Gagge