[go: up one dir, main page]

0% found this document useful (0 votes)
6 views8 pages

Union in C Programming

Union is a collection of variables of different data types, in case of union information can only be stored In one field at any one time. A union is a special data type available in C that enables you to store different data types in the same memory location.

Uploaded by

cscprabh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views8 pages

Union in C Programming

Union is a collection of variables of different data types, in case of union information can only be stored In one field at any one time. A union is a special data type available in C that enables you to store different data types in the same memory location.

Uploaded by

cscprabh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 8

LECTURE NOTE 26

UNION
Union is a collection of variables of different data types, in case of union information can only be
stored In one field at any one time. A union is a special data type available in C that enables you
to store different data types in the same memory location. You can define a union with
many members, but only one member can contain a value at any given time. Unions provide an
efficient way of using the same memory location for multi-purpose.

Declaring Union

union union-name

data_type var-name;

data_type var-name;

};

The union tag is optional and each member definition is a normal variable definition, such as int
i; or float f; or any other valid variable definition. At the end of the union's definition, before the
final semicolon, you can specify one or more union variables but it is optional. Here is the way
you would define a union type named Data which has the three members i, f, and str. Now,
a variable of Data type can store an integer, a floating-point number, or a string of characters.
This means that a single variable ie. same memory location can be used to store multiple types of
data. You can use any built-in or user defined data types inside a union based on your requirement.

The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in above example Data type will occupy 20 bytes of memory space because this is
the maximum space which can be occupied by character string. Following is the example which
will display total memory size occupied by the above union:
iq = ip

copies the contents of ipinto iq, thus making iqpoint to whatever ippointed to.

Pointers and Function Arguments


Since C passes arguments to functions by value, there is no direct way for the called function
to alter a variable in the calling function. For instance, a sorting routine might exchange
two out-
oforder arguments with a function called swap. It is not enough to write

swap(a, b);

where the swap function is defined as

void swap(int x, int y)


{
int temp;
t
e
m
p

x
;

y
;
y

t
e
m
p
;
}

Because of call by value, swap can't affect the arguments a and b in the routine that called
it. The function above swaps copies of a and b. The way to obtain the desired effect is
for the calling program to pass pointers to the values to be changed:

swap(&a, &b);
LECTURE NOTE 28

Pointers and Arrays


In C, there is a strong relationship between pointers and arrays, strong enough that pointers
and arrays should be discussed simultaneously. Any operation that can be achieved
by array subscripting can also be done with pointers. The pointer version will in general be
faster but, at least to the uninitiated, somewhat harder to understand. The declaration

int a[10];

defines an array of size 10, that is, a block of 10 consecutive objects named a[0], a[1], .,a[9].
The notation a[i] refers to the i-th element of the array. If pa is a pointer to an integer, declared
as

int *pa;
then the assignment

pa = &a[0];

sets pa to point to element zero of a; that is, pa contains the address of a[0].
Now the assignment

x =*pa;

will copy the contents of a[0] into x.


If pa points to a particular element of an array, then by definition pa+1 points to the
next element, pa+ipoints ielements after pa, and pa-ipoints ielements before. Thus, if pa

points to a[0], *(pa+1) refers to the contents of a[1], pa+iis the address of a[i], and *(pa+i)

is the contents of a[i]. These remarks are true regardless of the type or size of the variables in
the array
a. The meaning of ``adding 1 to a pointer,'' and by extension, all pointer arithmetic, is that
pa+1

points to the next object, and pa+ipoints to the i-th object beyond pa. The
correspondence between indexing and pointer arithmetic is very close. By definition, the
value of a variable or expression of type array is the address of element zero of the array. Thus
after the assignment

pa = &a[0];

pa and a have identical values. Since the name of an array is a synonym for the location of
the initial element, the assignment pa=&a[0] can also be written as
LECTURE NOTE 29
Address Arithmetic
If p is a pointer to some element of an array, then p++ increments p to point to the next element, and p+=iincrements it to point ielements beyond where it currently does.

These and similar


constructions are the simples forms of pointer or address arithmetic. All types of arithmetic operations are not possible with pointers. The valid operations that can
be performed using pointers are
(i) Addition of an integer to a pointer and increment operation.
(ii) Subtraction of an integer from a ponter and decrement operation.

(iii) Subtraction of a pointer from another pointer of same type.

The arithmetic operations that cannot be performed on pointers are as follows

(iv) Addition, multiplication and division of two pointers.


(v)Multiplication between pointer and any number. (iii)Division of a pointer by any number.
(iv) Addition of float or double values to pointers.

The expression p+1 yields the correct machine address for the next variable of that type. Other valid pointer expressions:

p+i, ++p, p+=I, p-q

where p-q represents the No of array elements between p and q.


Since a pointer is just a mem address, we can add to it to traverse an array. p+1 returns a ptr to the next array element.
Precedence level of * operator and increment/decrement operators is same and their associativity
is from right to left. In reality, p+1 doesn’t add 1 to the memory address, it adds the size of the array element.
Suppose p is an integer pointer and x is an integer variable. Now the main problem is to identify
how the following pointer expressions given below are interpreted.
(vi) x = *p++ is same as two expressions x = *p followed by p = p + 1.
(vii) x = (*p)++ is same as two expressions x = *p followed by *p = *p + 1.
(viii) x=*++p is same as two expressions p=p+1 followed by x=*p.
(ix) x=++*p is same as two expressions *p=*p+1 followed by x=*p

C is consistent and regular in its approach to address arithmetic; its integration of pointers, arrays, and address arithmetic is one of the strengths of the language. Let us
illustrate by writing a rudimentary storage allocator. There are two routines. The first, alloc(n), returns a pointer to n
consecutive character positions, which can be used by the caller of allocfor storing characters. The second, afree(p), releases the storage thus acquired so it can be reused later.
The routines are ``rudimentary'' because the calls to afreemust be made in the opposite order to the calls made
LECTURE NOTE 27

POINTERS

A pointer is a variable that contains the address of a variable. Pointers are much used in C,
partly because they are sometimes the only way to express a computation, and partly
because they usually lead to more compact and efficient code than can be obtained in other
ways. Pointers and arrays are closely related; this chapter also explores this relationship and
shows how to exploit it.
Pointers have been lumped with the goto statement as a marvelous way to create impossible to
understand programs. This is certainly true when they are used carelessly, and it is easy to
create pointers that point somewhere unexpected. With discipline, however, pointers can alsobe
used to achieve clarity and simplicity. This is the aspect that we will try to illustrate.
The main change in ANSI C is to make explicit the rules about how pointers can be manipulated,
in effect mandating what good programmers already practice and good compilers
already
enforce. In addition, the type void * (pointer to void) replaces char * as the proper type for a
generic pointer.

Pointers
of and
cells (often twoAddresses
or four) that can hold an address. So if c is a char

Let us begin with a simplified picture of how memory is organized. A typical machine has
and p is of
an array a consecutively
pointer that points to it, we
numbered could represent
or addressed memorythecells
situation this way:
that may be manipulated
individually
or in contiguous groups. One common situation is that any byte can be a char, a pair of one-byte
cells can be treated as a short integer, and four adjacent bytes form a long. A pointer is a group
The unary operator &gives the address of an object, so the statement

p = &c;

assigns the address of c to the variable p, and p is said to ``point to'' c. The &operator
only applies to objects in memory: variables and array elements. It cannot be applied to
expressions, constants, or register variables.
The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it
accesses the object the pointer points to. Suppose that x and y are integers and ipis a pointer to
int. This artificial sequence shows how to declare a pointer and how to use &and *:
The declaration of x, y, and z are what we've seen all along. The declaration of the pointer

ip. int *ip;

is intended as a mnemonic; it says that the expression *ipis an int. The syntax of the
declaration for a variable mimics the syntax of expressions in which the variable
might appear. This reasoning applies to function declarations as well. For example,

double *dp, atof(char *);

says that in an expression *dpand atof(s) have values of double, and that the argument
of
atofis a pointer to char.
You should also note the implication that a pointer is constrained to point to a particular kind
of
object: every pointer points to a specific data type. If ippoints to the integer x, then *ipcan
occur
in any context where x could, so

*ip = *ip + 10;

increments *ip by 10.

The unary operators * and &bind more tightly than arithmetic operators, so the assignment

y = *ip + 1

takes whatever ippoints at, adds 1, and assigns the result to y, while

*ip += 1

increments what ippoints to, as do

ip instead of what it points to, because unary operators like and associate right to left.
++*ip and (*ip)++ * ++
Finally, since pointers are variables, they can be used without dereferencing. For example, if iq is
The parentheses are necessary in this last example; without them, the expression would
another pointer to int,
increment
on alloc. That is, the storage managed by allocand afree is a stack, or last-in, first-out. The
standard library provides analogous functions called malloc and free that have no
such restrictions.
The easiest implementation is to have allochand out pieces of a large character array that we will
call allocbuf. This array is private to allocand afree. Since they deal in pointers, not array
source
indices, file containing
no other routine need know and thus be invisible
alloc and the name
afree , of the array, which can be declared static in the
outside it. In practical
implementations, the array may well not even have a name; it might instead be obtained
by calling mallocor by asking the operating system for a pointer to some unnamed block of
storage. The other information needed is how much of allocbufhas been used. We use a
pointer, called allocp, that points to the next free element. When allocis asked for n

characters, it checks to see if there is enough room left in allocbuf. If so, allocreturns the
current value of allocp(i.e.,
the beginning of the free block), then increments it by n to point to the next free area. If there
is no room, allocreturns zero. afree(p) merely sets allocpto pif p is inside allocbuf.

#define
ALLOCSI
ZE
10000

static
char
allocbu
f[ALLOC
SIZE];
static
char
*allocp
=
allocbu
f; char
*alloc(
int n)
{
if (allocbuf +
ALLOCSIZE - allocp>=
n) { allocp += n;
return allocp - n;
}

e
l
s
e
if (allocbuf + ALLOCSIZE - allocp>= n)

checks if there's enough room to satisfy a request for n characters. If there is, the new value
of allocpwould be at most one beyond the end of allocbuf. If the request can be
satisfied, allocreturns a pointer to the beginning of a block of characters (notice the
declaration of the
function itself). If not, allocmust return some signal that there is no space left. C guarantees that
zero is never a valid address for data, so a return value of zero can be used to signal an
abnormal event, in this case no space.
Pointers and integers are not interchangeable. Zero is the sole exception: the constant zero may
be assigned to a pointer, and a pointer may be compared with the constant zero. The
symbolic
constant NULL is often used in place of zero, as a mnemonic to indicate more clearly that this is a
special value for a pointer. NULL is defined in <stdio.h>. We will use NULL henceforth. Tests
like

if (allocbuf + ALLOCSIZE -
allocp>= n) and if (p >=
allocbuf&& p <allocbuf +
ALLOCSIZE)

show several important facets of pointer arithmetic. First, pointers may be compared under
certain circumstances. If p and q point to members of the same array, then relations like ==, !=,

<, >=, etc., work properly. For example,


p < q

is true if p points to an earlier element of the array than q does. Any pointer can be meaningfully
compared for equality or inequality with zero. But the behavior is undefined for arithmetic
or comparisons with pointers that do not point to members of the same array. (There
is one exception: the address of the first element past the end of an array can be used
in pointer arithmetic.) Second, we have already observed that a pointer and an integer may
be added or subtracted. The construction

p + n

means the address of the n-th object beyond the one p currently points to. This is true regardless

of the kind of object p points to; n is scaled according to the size of the objects p points

to,
which is determined by the declaration of p. If an intis four bytes, for example, the intwill be
scaled by four.

Pointer subtraction is also valid: if p and q point to elements of the same array, and p<q, then q-

You might also like