• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Fairly easy C++ question...

FrogDog

Diamond Member
Is it possible when initializing an array
char blah[2][5] = { "dog", "cat" };
to replace say "dog" with a variable? Such as this:
char blah[2][5] = { "cat", dog[cat-1] };

The way I just did it doesn't work, so is it possible and if so, how do I do it?

Edit - Forgot about the second [] on my char variables...oops 🙂
 
I think a good book on C (or C++) would suit you well.

char blah[2] is defining 'blah' as a 2-element array of type char. As you're probably aware, a single char cannot hold character arrays of themselves (dog, cat in your example). You would need:

char *blah[2] = { "dog", "cat" };

That would declare 'blah' as a 2-element array of pointers to type char. Does that make sense? As for your second example, yes, you can do that, although the declaration 'char blah[1]' is superfluous, as is '{dog[cat-1]}. It would suffice to say:

char blah = dog[1]; // or whatever

since blah[1] is defining 'blah' as a 1-element array of type char (same as just 'char blah'), and initializing it to the second character in the 'dog' character array.

Btw, your declaration 'char blah[1] = {dog[cat-1]}' could cause some serious problems. Assuming 'cat' is a character array, you're setting blah to the character at the address of the character _before_ the first character in 'cat'. Unless you know that the strings are perfectly aligned (which would still leave you w/ a nul character), you're asking for trouble.

Moral of the story, stick to declarations like char blah = your_char_array[index];

Hope this helps.
 
Oh crap yeah I messed up the code I'll edit it now...sorry.

And yeah in my [cat-1] part 'cat' is an int.
 
Back
Top