Sign in to follow this  
darenking

C++, trying to supply default values to a string of chars in a function header

Recommended Posts

Hello! I'm writing a class called Test that stores messages and prints them to the screen. I store the messages like this: char* m_Input[30]; Is that called an array of pointers to characters? Well, whatever it is called, it works fine, and when I use them I assign them like this: m_Input[i]="Hello there!"; This all works perfectly well, but I need an efficient way of supplying the 30 messages with default values ("empty"). At the moment I use a loop: for (int i=0 ; i<30 ; i++) { m_Input[i]="empty"; } I would rather supply default values in the constructor as surely it is neater that way? I tried this as my constructor prototype: Test(char* input="empty"); or Test(char* input[30]="empty"); then this as my constructor: Test::Test(char* input): m_Input[10](input) { } But it doesn't work and my head hurts. Actually they don't have to contain the literal "empty", they could just be empty: I just don't want them printing garbage on the screen! Thanks for any help! Joe

Share this post


Link to post
Share on other sites
Keep a count in the Test class so that you know how many messages that currently are stored. Or just initialize each pointer to NULL and check so that a message is not null whenever they are beeing used.

It seems that you cannot use default argument with arrays. Your example Test(char* input="empty") is legal syntax but you would still need a loop to initialize each element in the array. The correct syntax for initializing an array is: char *array[3] = {"string1", "string2", "string3"}

And by the way, that is a array of pointers to characters just as you thought.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this