Vijay C
Vijay C

Reputation: 4869

copy char* array in local variable

C++ newbie.

I have following class and its argument is char*, How do I copy that to member variable char* ? After that I need to know the size of array ?

class TestParam {

public:
  char*[] arr;
  TestParam (const char* Pre, char* Post[]){
    arr = Post;
  }
};
....
TestParam testParam[1] = { TestParam ("aa", (char*[]){"bb","cc","dd"})};

I know about std::string but I had to use char* because I am initializing the object like above in my code. Is it possible by std::string ?

Upvotes: 0

Views: 867

Answers (4)

user2249683
user2249683

Reputation:

#include <iostream>
#include <vector>

class TestParam {
    public:
    template <std::size_t N>
    TestParam(const char* pre, const char* (&arr_ref)[N]) {
        arr.reserve(N);
        for(const char* p: arr_ref) {
            if(p) arr.push_back(std::string(p));
        }
    }
    std::vector<std::string> arr;
};

int main() {
    const char* a[] = { "Hello", " " , "World" };
    TestParam param((char*)0, a);
    for(const std::string& s: param.arr) std::cout << s;
    std::cout << std::endl;
    return 0;
}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

I would suggest a solution where you use std::string and std::vector instead, like this:

class TestParam {
public:
    std::vector<std::string> arr;

    TestParam (const std::string& Pre, const std::vector<std::string>& Post){
        arr = Post;
    }
};

...

TestParam testParam[1] = { TestParam ("aa", {"bb","cc","dd"})};

Upvotes: 1

Useless
Useless

Reputation: 67743

You first need the number of elements in Post - that needs to be passed in as another argument, unless Post is defined to have a NULL last element, in which case you need to count the non-NULL elements first.

Once you know that, you can allocate memory for arr.

Finally, you can either perform a shallow copy by assigning the pointer values (eg. arr[i] = Post[i], or a deep copy by duplicating each string. You haven't told us which you need.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206546

You need to allocate sufficient memory to the destination pointer and then use std::copy.

Tip: Consider using std::string instead.

Upvotes: 2

Related Questions