473,795 Members | 2,911 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Difference between Structure & Union

Hi All,

Can you give me the example code which explains difference between
Structures and Union. As a newbie please do the needful.

Thanks,
csudha.
Nov 14 '05 #1
4 21008


csudha wrote:
Hi All,

Can you give me the example code which explains difference between
Structures and Union. As a newbie please do the needful.

Thanks,
csudha.


struct and union are defined in the same way; a structure stores its
members at unique memory locations, and a union stores its members in
the same place.

struct { int a; int b; } str;
union { int a; int b; } uni;

str.a=1; str.b=2; printf("%d",str .a); // prints 1.
uni.a=1; uni.b=2; printf("%d",uni .a); // prints 2.

The usual example is of a spreadsheet that stores a number, a formula or
some text in a cell; you have a struct for the cell that contains a
variable indicating what is stored in the cell, and a union of a number,
formula and string; and the value of the indicator determines to which
member of the union you read and write.

Dave.
Nov 14 '05 #2
On 10 Sep 2004 07:02:08 -0700, su**********@ya hoo.com (csudha) wrote:
Hi All,

Can you give me the example code which explains difference between
Structures and Union. As a newbie please do the needful.

In a union, all the members overlay each other and start at the
beginning of the union.

In a struct, the members do not overlap at all and are stored
sequentially (but not necessarily adjacently) in the struct in the
same order they are defined.
<<Remove the del for email>>
Nov 14 '05 #3
csudha wrote:

Hi All,

Can you give me the example code which explains difference between
Structures and Union. As a newbie please do the needful.


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.)

==========
#include <stdio.h>

struct foo
{
char c;
long l;
char *p;
};

union bar
{
char c;
long l;
char *p;
};

int main(int argc,char *argv[])
{
struct foo myfoo;
union bar mybar;

myfoo.c = 1;
myfoo.l = 2L;
myfoo.p = "This is myfoo";

mybar.c = 1;
mybar.l = 2L;
mybar.p = "This is mybar";

printf("myfoo: %d %ld %s\n",myfoo.c,m yfoo.l,myfoo.p) ;
printf("mybar: %d %ld %s\n",mybar.c,m ybar.l,mybar.p) ;

return 0;
}

==========

On my system, I get:

myfoo: 1 2 This is myfoo
mybar: 100 4197476 This is mybar

Note how all of the "myfoo" elements are intact, whereas only the
"mybar.p" entry is intact, as the others have been overwritten by the
assignment to mybar.p.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Nov 14 '05 #4
Kenneth Brody <ke******@spamc op.net> wrote in message news:<41******* ********@spamco p.net>...
csudha wrote:

Hi All,

Can you give me the example code which explains difference between
Structures and Union. As a newbie please do the needful.

Hi CSuda,

Now you be trained, how to post Q and Doubts in this Group. Good.
Keep it up.

Seenivasan (Vasu)


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.)

==========
#include <stdio.h>

struct foo
{
char c;
long l;
char *p;
};

union bar
{
char c;
long l;
char *p;
};

int main(int argc,char *argv[])
{
struct foo myfoo;
union bar mybar;

myfoo.c = 1;
myfoo.l = 2L;
myfoo.p = "This is myfoo";

mybar.c = 1;
mybar.l = 2L;
mybar.p = "This is mybar";

printf("myfoo: %d %ld %s\n",myfoo.c,m yfoo.l,myfoo.p) ;
printf("mybar: %d %ld %s\n",mybar.c,m ybar.l,mybar.p) ;

return 0;
}

==========

On my system, I get:

myfoo: 1 2 This is myfoo
mybar: 100 4197476 This is mybar

Note how all of the "myfoo" elements are intact, whereas only the
"mybar.p" entry is intact, as the others have been overwritten by the
assignment to mybar.p.

Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2156
by: Claudio | last post by:
hi all i put in this email source code so u can copy and paste to verify strange first : in this example bit size is a BYTE ?! second : in the last printf output is wrong ? ? best regards all
2
6468
by: yee young han | last post by:
I need a fast data structure and algorithm like below condition. (1) this data structure contain only 10,000 data entry. (2) data structure's one entry is like below typedef struct _DataEntry_ { char szInput; char szOutput; int iSum;
5
575
by: pt | last post by:
Hi, i am wonderng what is faster according to accessing speed to read these data structure from the disk in c/c++ including alignment handling if we access it on little endian system 32 bits system + OS e.g. Windows, Linux, WinCE. I am not quite sure about the alignment of the memory.... soln. 1: should be faster, I am not sure. idx size (bytes) 1 4
5
2645
by: xmllmx | last post by:
Please forgive me for cross-posting. I've post this to microsoft.publoc.vc.mfc. But I can't get any response. Maybe only MFC- related topics are cared there. To begin with code: union XXX { double a; char b;
0
1348
by: manish sahu | last post by:
difference between structure and union ,, can anyone help me?
6
4105
by: npd1 | last post by:
what is the difference between structure & union
14
28169
by: deepak | last post by:
Hi Experts, I'm getting this compilation error while trying to access a member in structure. at what time we will get this error message? Thanks, Deepak
5
6390
by: hnshashi | last post by:
I have writtem kernel(2.4) module to commu. with user space appl. using netlink socket. I am getting compilation error. kernel module:-> #include <linux/skbuff.h> #include<linux/module.h> #include <linux/socket.h> #include <linux/config.h> #include <linux/module.h> #include <linux/kernel.h>
3
11590
by: burak aktas | last post by:
hi there i am trying to build a linked list from read a file operation. this code only adds the first node to the list. the problem is i am facing with "error: request for member 'head' in something not a structure or union" error. here is the code; #include <stdio.h> #include <stdlib.h> #include <string.h> #include "PR-ADT.h" void add_Node(LIST** , NODE*); LIST* create_list(void);
0
10439
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10215
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10165
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9043
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7541
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6783
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.