如何声明已在类中声明的char变量的Char数组?

时间:2013-08-16 04:54:26

标签: c++ arrays variables pointers char

#include <stdio.h>
#include <iostream>

using namespace std;

//char* b[6] = new char[6];

char a[6] = {'b','c','d','e','f','g'};
char c[6] = {'a','b','d','d','f','g'};

int main()
{
    char d[][6]={*a,*c};



    for (int x = 0 ; x < 1; x++)
    {
        for(int y = 0; y<6; y++)
        {
            char test = d[x][y];
            cout << test <<"\n";
        }
    }
    return 0;
}

此代码是C ++代码。我正在尝试创建一个存储char数组的类。然后有另一个char数组存储已声明的char变量。它编译得很好,但它不能正常工作。当程序试图打印值

时,它没有得到正确的值

4 个答案:

答案 0 :(得分:2)

可能是指一系列指针:

char *d[]={a,c};

答案 1 :(得分:1)

typedef std::vector<char>          VectorChar;
typedef std::vector< VectorChar* > VectorVectorChar;

struct V
{
  V() : _v{ '0', '1', '2' } {}

  VectorChar _v;
};

int main(void)
{
    V arrV[5];

    VectorVectorChar vvc;
    for ( auto& v : arrV )
       vvc.push_back( &v._v );

    // print them
    for ( auto pV : vvc )
    {
      for ( auto c : *pV )
          cout << c << ' ';
      cout << '\n;
    }

    return 0;
}

答案 2 :(得分:0)

我从这个问题中理解,你想创建用于存储已经初始化的char数组的类。

#include <stdio.h>
#include <iostream>

    char a[6] = {'b','c','d','e','f','g'};  // Initialized character array. MAX 6

    // This class will hold char array
    class Test {    
    public:
        void setName(char *name);
        const char* getName();
    private:
        char m_name[6]; // MAX 6 ( since you already initialized(MAX 6), So no need dynamic memory allocation. )
    };

    void Test::setName(char *name) {
        strcpy(m_name, name); // Copy, already initialized array
    }

    const char* Test::getName() {
        return m_name;
    }

   int main(int argc, char** argv) {
    {
        Test foobar;       
        foobar.setName( a );  // set the pointer which point to starting of the initialized array.
        cout << foobar.getName();
        return 0;
    }

答案 3 :(得分:0)

char a[6] = {'b','c','d','e','f','\0'};
char c[6] = {'a','b','d','d','f','\0'};
char* d[]= {a,c};

for (int x = 0 ; x < 2; x++)
{
    for(int y = 0; y < 6; y++)
    {
        char test = d[x][y];
        cout << test << "\n";
    }
}

return 0;