Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Dynamic array of fixed length strings

How do I create a dynamic array of fixed length strings?

I created class AString which has pointers to struct _str which has fixed-length array data.

How to assign values, and what is wrong?

#include "stdafx.h"
#include <iostream>

struct _str {
    char data[20];
};

class AString {
public:
    AString();
    ~AString();
    void Add(_str string);
private:
    _str *str;
    int count;
};

AString::AString() {
    std::cout << "Constructor" << std::endl;
    str = nullptr;
    count = 0;
}

AString::~AString() {
    std::cout << "Destructor" << std::endl;
    if (str != nullptr) delete[] str;
}

void AString::Add(_str string) {
    _str *str2 = new _str[count+1];
    for (int i=0;i<count;i++) {
        str2[i] = str[i];
    }
    delete[] str;
    str = str2;
    count++;
    str[count-1] = string;
}

int _tmain(int argc, _TCHAR* argv[])
{
    AString astring;
    _str str1;
    str1.data="0123456789012345678"; // cannot convert from 'const char[20]' to 'char[20]'
    astring.Add(str1);
    std::cin.get();
    return 0;
}

str1.data="0123456789012345678";: cannot convert from 'const char[20]' to 'char[20]'

Want to: not use _str str1;, and use char str1[20];

question from:https://stackoverflow.com/questions/65938363/dynamic-array-of-fixed-length-strings

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

1 Answer

0 votes
by (71.8m points)

As for me, I used this:

   strcpy(str1.data, "0123456789012345678");

Here is the main:

int main(int argc, char* argv[])
{
    AString astring;
    _str str1;
    //str1.data=const_cast<char>("0123456789012345678"); // cannot convert from 'const char[20]' to 'char[20]'
    strcpy(str1.data, "0123456789012345678");
    astring.Add(str1);

    std::cout << str1.data;
    std::cin.get();
    return 0;
}

The result is as follows:

Constructor
0123456789012345678

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...