How can I initialize char arrays in a constructor?

arrays, c++, char

Solution

If there are no particular reasons to not use `std::string`, do use `std::string`.

But if you really need to initialize that character array member, then:

#include <assert.h>
#include <iostream>
#include <string.h>
using namespace std;

class test
{
    private:
        char name[40];
        int x;
    public:
        test();
        void display() const
        {
            std::cout<<name<<std::endl;
        }
};

test::test()
{
    static char const nameData[] = "Standard";

    assert( strlen( nameData ) < sizeof( name ) );
    strcpy( name, nameData );
}

int main()
{
    test().display();
}

Problem

I'm having trouble declaring and initializing a char array. It always displays random characters. I created a smaller bit of code to show what I'm trying in my larger program: ``` class test { private: char name[40]; int x; public: test(); void display() { std::cout<<name<<std::endl; std::cin>>x; } }; test::test() { char name [] = "Standard"; } int main() { test *test1 = new test; test1->display(); } ``` And sorry if my formatting is bad, I can barely figure out this website let alone how to fix my code :(

Original source

Related problems