简体   繁体   中英

Initializing to a dynamically allocated const char array from a const char array

I am trying to write code that will assign a const char array to a dynamically allocated const char array. I tried to do it like

const char staticArray[4] = "abc";
const char * ptrDynamicArray;
ptrDynamicArray = new const char[4](staticArray);

But I get an error ("parenthesized initializer in array new [-fpermissive]").

I have two questions:

  1. How could I solve it - like turn it off (I am using Code::Blocks 16.01)?

  2. Can I initialize a dynamically allocated const char array somehow else?

Overloading new operator will do your job.

void * operator new[](size_t n, const char *s) {
    void *p = malloc(n);
    strcpy((char *)p, s);
    return p;
}

Now new operator can be called like :

const char staticArray[4] = "abc";
const char * ptrDynamicArray;
ptrDynamicArray = new (staticArray) char[4];

You cannot copy-initialize an array from another array directly, hence the error. You either need to manually copy the elements (or use std::copy ), or, better, if you want a "copy"-able array use std::array<char, 4> instead.

But, as mentioned in the comments, the best probably is to use an std::string here, and use its std::string::c_str() member function in case you need to pass around const char* pointers to old C-like interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM