2
#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

4 回答 4

2

可能你的意思是指针数组:

char *d[]={a,c};
于 2013-08-16T04:59:29.997 回答
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;
}
于 2013-08-16T05:23:07.243 回答
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;
于 2015-01-07T11:00:13.440 回答
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;
    }
于 2013-08-16T06:23:09.707 回答