views:

52

answers:

1

I was told to write a program, that creates a union and structure, then creates two-element arrays of unions and structures and fills their fields. I have created a union and a structure, but how to fill their fields in arrays ?

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

union complex;

union complex{
      int i1;
      long double ld1;
      } u;

struct Person {
    char* name;
    int age;
    bool sex;
    void show(){
    printf("name %s, age %2.0d, sex %1d\n",
        name , age, sex);        
    };
} person;

int main(void)
{ 

    Person *o = new Person[2];
    complex *un = new complex[2];

    un[0]->i1=i;  

    system("pause");
    return 0;
}

I've tried un[0]->i1=i; but it's not the proper way to do this.

+3  A: 

un is an array of complex, not an array of pointers to complex. Therefore, un[0] is a complex, not a pointer to a complex.

Thus, you need:

un[0].i1 = i;

The global instance of type complex called u looks a bit pointless, and should probably be removed.

unwind
okay, and let's say I have it set un[0].i1 = 6; . How to print it ?I was trying printf("i1 $2.0d", un[0].i1); but it prints me nothing.
newbDeveloper
it prints me properly values of structure fields but not union.
newbDeveloper
@newbDeveloper: It's best to edit the question, and copy-paste actual code. That looks like a formatting string error, you should use "%d" to print an int, there's no $ involved.
unwind