answersLogoWhite

0


Best Answer

A union is a way of providing an alternate way of describing the same memory area. In this way, you could have a struct that contains a union, so that the "static", or similar portion of the data is described first, and the portion that changes is described by the union. The idea of a union could be handled in a different way by having 2 different structs defined, and making a pointer to each kind of struct. The pointer to struct "a" could be assigned to the value of a buffer, and the pointer to struct "b" could be assigned to the same buffer, but now a->somefield and b->someotherfield are both located in the same buffer. That is the idea behind a union. It gives different ways to break down the same buffer area.

The difference between structure and union in c are: 1. union allocates the memory equal to the maximum memory required by the member of the union but structure allocates the memory equal to the total memory required by the members. 2. In union, one block is used by all the member of the union but in case of structure, each member have their own memory space

Difference in their Usage:While structure enables us treat a number of different variables stored at different in memory , a union enables us to treat the same space in memory as a number of different variables. That is a Union offers a way for a section of memory to be treated as a variable of one type on one occasion and as a different variable of a different type on another occasion.

There is frequent rwquirement while interacting with hardware to access access a byte or group of bytes simultaneously and sometimes each byte individually. Usually union is the answer.

=======Difference With example***** Lets say a structure containing an int,char and float is created and a union containing int char float are declared. struct TT{ int a; float b; char c; } Union UU{ int a; float b; char c; }

sizeof TT(struct) would be >9 bytes (compiler dependent-if int,float, char are taken as 4,4,1)

sizeof UU(Union) would be 4 bytes as supposed from above.If a variable in double exists in union then the size of union and struct would be 8 bytes and cumulative size of all variables in struct.

Detailed Example:struct foo

{

char c;

long l;

char *p;

};

union bar

{

char c;

long l;

char *p;

};

A struct foo contains all of the elements c, l, and p. Each element is

separate and distinct.

A union bar contains only one of the elements c, l, and p at any given

time. Each element is stored in the same memory location (well, they all

start at the same memory location), and you can only refer to the element

which was last stored. (ie: after "barptr->c = 2;" you cannot reference

any of the other elements, such as "barptr->p" without invoking undefined

behavior.)

Try the following program. (Yes, I know it invokes the above-mentioned

"undefined behavior", but most likely will give some sort of output on

most computers.)

======= Union allocates the memory equal to the maximum memory required by the member of the union but structure allocates the memory equal to the total memory required by the members. In union,one block is used by all the member of the union but in case of structure, each member have their own memory space.

Union allocates the memory equal to the maximum memory requried by the member of the union but structure allocates the memory equal to sum of the memory allocated to its each individual members.

In Union, one block is used by all the member of union but in case of structure, each member have their own memory space.

Union allocates the memory equal to the maximum memory requried by the member of the union but structure allocates the memory equal to total memory requried by the members. In Union, one block is used by all the member of union but in case of structure, each member have their own memory space.

User Avatar

Wiki User

8y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

12y ago

C does not have a class, as classes are an Object-Oriented structure. In OO methodology, a class is a definition from which an object reference is instantiated. A C struct is a flat memory structure defining a data-type, which is a grouping of variables or references of varying types. Pascal uses the "record" type to define the same thing.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

In a struct(ure), the data items are sequentially layed out in memory, and they are separate and distinct. In a union, they all have the same address, allowing you to store different things in the union, but only one at a time.

One thing that unions allow you to do is to inspect the internal bit patterns of other things, such as by mapping a floating point variable to a character array.

union {

float f;

unsigned char c[4];

} myUnion;

myUnion.f = 1.234;

printf (%u %u %u %u\n", myUnion.c[0], myUnion.c[1], myUnion.c[2], myUnion.c[3]);

However, this is highly platform dependent, non-portable, and not recommended.

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

A structure is an aggregate of members that each have their own memory address. The size of a structure is the sum of the sizes of its members plus any padding required for memory alignment purposes.

A union is an aggregate of members that share the same memory address. The size of a union is equal to the length of the largest member.

This answer is:
User Avatar

User Avatar

Wiki User

14y ago

In C++, and also C and Java, a structure is a set of related items that are contained within another item, the "structure", and can be treated as one (larger) item. A record in a database, for instance, can be considered to be a structure, where each item in the structure corresponds to a field in the database record.

A union, on the other hand, while looking like a structure, is a set of items that are contained within another item, the "union", but, unlike a structure, can only contain one of the defined items at a time. The items actually occupy the same memory space and, though non-portable, can be used to inspect the bit patterns of more complex items, such as floating point numbers, treated as integers. Think of a union as a database record which can contain different types of fields, but only one field at a time.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

A structure is simply a class, but one that has public access by default (classes are private by default). A union is similar to a structure or class except that all members of a union have the same start address, rather than contiguous addresses, and allows you to map different types to the same memory (the amount of memory allocated is dependent upon the largest member). Thus if you have a structure with 4 embedded char types, you can make a union that treats that structure as if it were really a 32-bit int or access each individual byte within that int without the need for a char pointer. If you have another structure with two 16-bit shorts then you can map those 4 chars to two pairs of chars, and so on. Unions and structures can also inherit from each other.

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

A union is an aggregate of different data types that all share the same start address. The length of a union is determined by the largest member of the union. A union can store one value and one value only. The actual value stored in the union is determined by whichever member the value was assigned to. Accessing any member other than the one to which the value was assign results in a re-interpretation of that value, according to the member's type.

Unions are useful when you have a number of types but only need to store one value at any one time. Rather than storing these types separately they all share the same address space, so you use less memory.


A structure is an aggregate of data types, each of which has a different address offset within the structure. Each member is independent. The length of a structure is determined by the sum of its member lengths, plus any padding required for alignment purposes. To minimise padding, members should be declared in order of size, largest first.


Structures are useful when you have a number of types that are related. For instance, a person's name may be divided into forename, surname and middle initials. These would be formed from three separate strings (character arrays) but would need to be treated as being a single entity. By storing these strings in a structure, you create a complex type that has three members, each of which can be accessed individually, much like a database record.


A class is an extension of a structure, such that the structure has member functions as well as member data. This allows the programmer to combine data with the functions that specifically operate upon that data. Moreover, the data itself can be declared private such that only member functions of the class may gain direct access to that data. The programmer can declared public functions that allow the user of the class to manipulate the data in a more controlled and consistent manner than is possible with a structure alone. With a structure, any function can access the data, placing the onus of responsibility upon the programmer to ensure the integrity of the data remains in a valid state. Classes shift the onus of responsibility to the class itself.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

Unions save memory by overlapping each member of the union's memory in a way that you can effectively use only one member of the union at a time. This is useful when only one value will be used at a time out of several different types of data, or some limited cases where you want to access different parts of the same data (usually in bytes) without using functions.

A struct allocates memory for each member, such that all members can be used at once. This is the most common type of complex data structure, as all members can be used at once, which is usually what a developer needs.

This answer is:
User Avatar

User Avatar

Wiki User

14y ago

they are similar in collection of logical elements but they are different in memory allocation to the variables.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Difference between struct and union
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

Difference between array and union?

All the members of the structure can be accessed at once,where as in an union only one member can be used at a time. Another important difference is in the size allocated to a structure and an union. for eg: struct example { int integer; float floating_numbers; } the size allocated here is sizeof(int)+sizeof(float); where as in an union union example { int integer; float floating_numbers; } size allocated is the size of the highest member. so size is=sizeof(float);


What is the difference between class and struct?

The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive. When we create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized. It is an error to declare a default (parameterless) constructor for a struct. A default constructor is always provided to initialize the struct members to their default values. It is an error to initialize an instance field in a struct. There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do. A struct is a value type, while a class is a reference type.


What is the difference between structures in C and structures in CPP?

A struct (structure) is the same, whether you use C or C++, so, depending on your point of view, there is no difference. In C++, however, a struct is a class that has no methods, not even a constructor or destructor (except for the default ones), and its default inheritance model is public instead of private.


What is the difference between struct in c and c plus plus?

In C, a struct is simply a type that can hold several sub-objects. In C++, struct is almost the same as "class". It can have member functions, parent structs and classes, etc. The only difference between struct and class is that the members of class are by default private, while the members of struct are by default public. Thus, a standard C struct is also a good C++ struct - simply one that has no member functions and no parents.


Can structures be nested in c?

yes. struct a { int x; int y; } struct b{ int z; struct a w; }

Related questions

What is the difference between struct and union in c file management?

The main difference is in how the data structures are stored. In a union, all of the elements are stored in one location. A structure stores each of its elements in a separate memory location.


Similarities between struct and union?

Struct and Union have following similarities:- Both are aggregated data types that allow a mixed for values to be contained in their instances.They are the way aggregation is done in C for making. The difference between them is that union allows the different items to be in it but allows access to be on one becase they are represented in overlapped manner. A Struct is also aggregation but it separates each data item contained in it and therefore anyone can be accessed anytime from its instance variable.Unions are ordinarily used because of performance and generalization ,while the structures are generally used for aggregation. For queries Rupesh Kumar Joshi ,rupesh_joshi@sify.com


Difference between central government and union government?

There is no difference between central and union government


Difference between array and union?

All the members of the structure can be accessed at once,where as in an union only one member can be used at a time. Another important difference is in the size allocated to a structure and an union. for eg: struct example { int integer; float floating_numbers; } the size allocated here is sizeof(int)+sizeof(float); where as in an union union example { int integer; float floating_numbers; } size allocated is the size of the highest member. so size is=sizeof(float);


What is difference between struct variable and class object?

structure variable can access the variable but class object can access the function also


Similarities between C plus plus struct and class?

The only difference between a struct and a class in C++ is that struct members are public by default while class members are private by default. Other than that they act and behave in exactly the same way and are both used to define classes. By convention, struct is used exactly as it would be used in C, with all public members and no member functions, to provide backward compatibility with C-style code.


Does structure support polymorphism?

Yes. The only difference between a struct and a class is that a struct's members and inheritance is public by default, while a class' members and inheritance are private by default. Structs can derive from classes and classes can derive from structs. As such, they are polymorphic.


What is the difference between declaring variable and initializing variables?

Actually, there is a third step, call definition. Declaration is a statement to the compiler of what type an identifier is, definition is the allocation of memory for that identifier, and initialization is the assignment of an initial value to that identifier. Usually, declaration and definition are done together, but you can also add initialization in that step if desired. int a; /* declaration and definition */ a = 1; /* initialization */ int a = 1; /* declaration, definition, and initialization */ For the case of seperate declaration and definition, consider the struct... struct _mystruct { int a; }; /*declaration */ struct _mystruct mystruct; /* definition */ struct _mystruct { int a; } mystruct; /*declaration and definition */ Note: To be more precise: struct _mystruct; /* struct declaration */ struct _mystruct { int a; }; /* struct definition */ typedef struct _mystruct MYTYPE; /* type definition */ extern struct _mystruct mystructvar; /* variable declaration */ struct _mystruct mystructvar; /* variable definition */ struct _mystruct mystructvar = {7} ; /* variable definition with initialization */ struct _mystruct { int a; } mystruct; /* struct definition and variable definition */ extern struct _mystruct { int a; } mystruct; /* struct definition and variable declaration */


What is the Difference of anti union policy between union avoidance?

The difference is that you are not putting down the union, you are uplifting the company. You are talking about the positive benefits or the organization vs. the negative benefit of a union.


Do Americans know the difference between Rugby league and Rugby Union?

In general those that follow union or league know the difference.


Could you Cite examples to show difference between structures and classes?

The only difference between a struct and a class is that struct members are public by default while class members are private by default. To demonstrate, consider the following code: #include<iostream> struct struct_object { int m_data; }; class class_object { int m_data; }; int main() { struct_object s; class_object c; s.m_data = 42; // ok -- s.m_data has public access by default. c.m_data = 42; // access denied -- c.m_data is private by default. }


What was the difference between the Confederacy and the Union?

the union has more factories and bigger population than the confederacy.