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 :(
Considering you tagged the question as C++, you should use
std::string
:Your constructor is not setting the member variable
name
, it's declaring a local variable. Once the local variable goes out of scope at the end of the constructor, it disappears. Meanwhile the member variable still isn't initialized and is filled with random garbage.If you're going to use old-fashioned character arrays you'll also need to use an old-fashioned function like
strcpy
to copy into the member variable. If all you want to do is set it to an empty string you can initialize it withname[0] = 0
.c++11 actually provides two ways of doing this. You can default the member on it's declaration line or you can use the constructor initialization list.
Example of declaration line initialization:
Example of constructor initialization:
You can see a live example of both of these here: http://ideone.com/zC8We9
My personal preference is to use the declaration line initialization because:
Having said all this, using a
char[]
may be considered damaging as the generated default assignment operator, and copy/move constructors won't work. This can be solved by:const
char*
(this won't work if the member will hold anything but a literal string)std::string
should be preferredSince you are using C++, I suggest using strings instead of char arrays. Otherwise you'd need to employ strcpy (or friends).
Also, you forgot to delete the test1 instance.
If there are no particular reasons to not use
std::string
, do usestd::string
.But if you really need to initialize that character array member, then: