Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

c++ - Assigning char x[] array to char* ptr

I receive a character address and I want to have the character pointer hold the values in the character array

void assign(char set[]) {
    m_ptr = new char[strlen(set) + 1];
    strcpy(m_ptr, set);

    // OR

    m_ptr = set;

Are both ways okay? I also want to avoid memory leak as well, but I do have a destructor so I figure I am fine.

~Title() {
    delete[] m_ptr;
}
question from:https://stackoverflow.com/questions/65875424/assigning-char-x-array-to-char-ptr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First version

void assign(char set[]) {
    m_ptr = new char[strlen(set) + 1];
    strcpy(m_ptr, set);

This code creates a new character array and copies the characters from the old array to the new one. So you end up with two character arrays and two pointers, each pointing at one of the character arrays. Both array contents are the same however.

Second version

void assign(char set[]) {
    m_ptr = set;

This time no new character array is created, instead you copy the pointer, so there is only one character array and both pointers point at it.

These are very different outcomes and it's really up to you to decide which one is best for you. Normally however the first is preferred. The problem with the second is that you end up with two pointing pointing at the same data. In this situation any changes to the array will be seen by both pointers, which is potentially confusing. Also if the array needs deleting then it's not clear whose responsibility that is, since either pointer could be used to delete the array.

So I would use the first version unless you feel you have a strong reason not to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...