Dynamically allocating structures. HW question.

cheers
Last edited on
what am I doing something wrong?
There is nothing wrong with it. That's the way union work. And yes: it's a good idea to have the type of the code.

You cannot change the enum (at runtime), but you can very well change the value of charType

[EDIT] The second struct is supposed to look like this:
1
2
3
4
5
6
7
8
9
10
11
12
struct CharacterNode
{

union charCode
{
	char AsciiCode;
	unsigned char EbcdicCode;
	unsigned short UnicodeCode;
} CharCode; // Note

enum CharType { ASCII, EBCDIC, UNICODE } charType; // Note
};
You can use both
Last edited on
Thank you very much! So when the question asks,
Your code should populate and display all three CharacterTypes
What exactly is it asking? Because the character types are the enums.
Use an arrray, like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;

union CharacterCodes
{
	char AsciiCode;
	unsigned char EbcdicCode;
	unsigned short UnicodeCode;
};

enum CharacterType { ASCII, EBCDIC, UNICODE };

struct CharacterNode
{
	CharacterType charType;
	CharacterCodes CharCode;
};

int main()
{
	CharacterNode* charPtr = nullptr;
	charPtr = new CharacterNode[3]; // Note
	charPtr[0].charType = ASCII;
	charPtr[0].CharCode.AsciiCode = 'a';
	charPtr[1].charType = UNICODE;
	charPtr[1].CharCode.UnicodeCode = 'b';
	charPtr[2].charType = EBCDIC;
	charPtr[2].CharCode.EbcdicCode = 501;

for(int i = 0; i < 3; ++i)
{
    // show charPtr[i]
}

}
Topic archived. No new replies allowed.