Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Whats wrong with this code. I keep getting a excess elements in aggregate initializer error.



#include <iostream.h>
#include <stdlib.h>

union UVar
{
char A[5];
int I[10];
float k[8];
};

void main()
{
UVar total = {&quot;STUF&quot;, 346576536, 13423.585};
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << total.A << *total.I << *total.k << endl;

system(&quot;PAUSE&quot;);
return 0;
}
 
A few code gremlins

A union can only hold one of its data members at a time.
it uses the same memory space for each type of data member.

You dont need an int or float array to hold 1 number even if it has multiple digits

If you want to use a union, UVar total needs to be an array
and then each data member needs initialising individually
The output line needs to call each member of the array eg
Code:
UVar total[3]; 
strcpy(total[0].A,&quot;STUF&quot;);
total[1].I =  346576536;
total[2].k =  13423.585;
...
cout << total[0].A << total[1].I << total[2].k << endl;

The main function is return type void, you don't need return 0;

I would use a class with a constructor to initialise the class members eg:-
Code:
class UVar  
{
public:
//data members
	char A[5];
	int I;
	float k;

//constructors
	UVar();
	UVar(char *,int,float);

//destructor
	virtual ~UVar();
};

//main function
void main()
{
      UVar total(&quot;STUF&quot;, 346576536,  13423.585);
      cout.precision(2);
      cout.setf(ios::fixed | ios::showpoint);
      cout << total.A << total.I << total.k << endl;

      system(&quot;PAUSE&quot;);
}
//UVar class functions
UVar::UVar()
{
}
UVar::UVar(char *pszData,int nData,float fData)
{
	strcpy(A,pszData);
	I = nData;
	k = fData;
}
UVar::~UVar()
{
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top