Docsity

Programming in C language (Unit-3), Study notes of C programming

Partial preview of the text

Download Programming in C language (Unit-3) and more Study notes C programming in PDF only on Docsity!

ES-101/

Programming in C

Unit 3

MODULE 3

LECTURE NOTE 24

STRUCTURE AND UNION

Definition

A Structure is a user defined data type that can store related information together. The variable within a structure are of different data types and each has a name that is used to select it from the structure. C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in C programming, which allows you to combine data items of different kinds.

Structures are used to represent a record, Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:

  • Title
  • Author
  • Subject
  • Book ID

Structure Declaration

It is declared using a keyword struct followed by the name of the structure. The variables of the structure are declared within the structure.

Example:

Struct struct-name

{

data_type var-name;

data_type var-name;

QUESTIONS
  1. Write a program using structures to read and display the information about an employee.
  2. Write a program to read, display, add and subtract two complex numbers.
  3. Write a program to enter two points and then calculate the distance between them.

LECTURE NOTE 25

NESTED STRUCTURES

The structure that contains another structure as its members is called a nested structure or a structure within a structure is called nested structure. The structure should be declared separately and then be grouped into high level structure.

  1. Write a program to read and display the information of all the students in the class using nested structure.

Passing Structures through pointers

Pointer to a structure is a variable that holds the address of a structure. The syntax to declare pointer to a structure can be given as:

strcut struct_name *ptr;

To assign address of stud to the pointer using address operator(&) we would write

ptr_stud=&stud;

To access the members of the structure (->) operator is used.

for example

Ptr_stud->name=Raj;

SELF REFERENTIAL STRUCTURE

Self –referential structures are those structures that contain a reference to data of its same type as that of structure.

Example

struct node

{

int val;

struct node*next;

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:

Accessing a Member of a Union

_#include _

_#include _

union Data

{

int i; float f;

char str[20];

};

int main( )

{ union Data data; data.i = 10;

data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f);

printf( "data.str : %s\n", data.str);

return 0;

}

Dot operator can be used to access a member of the union. he member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type. Following is the example to explain usage of union:

Exercises:

  1. Write a program to define a union and a structure both having exactly the same members. Using the sizeof operator, print the size of structure variable as well as union variable and comment on the result.
  2. Write a program to define a structure for a hotel that has the member’s mane, address, grade, number of rooms, and room charges. Write a function to print the names of the hotels in a particular grade. Also write a function to print names of a hotel that have room charges less than the specified value.

int x = 1, y = 2, z[10]; int *ip; ip = &x; y = *ip; *ip = 0; ip = &z[0];

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 and (ip)++

The parentheses are necessary in this last example; without them, the expression would increment

ip instead of what it points to, because unary operators like (^) * and (^) ++ associate right to left. Finally, since pointers are variables, they can be used without dereferencing. For example, if (^) iq is

another pointer to (^) int,

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; temp = x; x = y; y = temp; } 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);

Since the operator & produces the address of a variable, &a is a pointer to a. In swap itself, the parameters are declared as pointers, and the operands are accessed indirectly through them.

void swap(int *px, int py) / interchange *px and *py */ { int temp; temp = *px;

*px = *py; *py = temp; }

Pointer arguments enable a function to access and change objects in the function that called it. As

an example, consider a function (^) getint that performs free-format input conversion by breaking a

stream of characters into integer values, one integer per call. (^) getint has to return the value it

found and also signal end of file when there is no more input. These values have to be passed

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+ 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

pa = a;

Rather more surprising, at first sight, is the fact that a reference to (^) a[i] can also be written as

*(a+i). In evaluating (^) a[i], C converts it to (^) *(a+i) immediately; the two forms are equivalent.

Applying the operator (^) &to both parts of this equivalence, it follows that (^) &a[i] and (^) a+iare also

identical: (^) a+iis the address of the (^) i-th element beyond (^) a. As the other side of this coin, if (^) pa is a

pointer, expressions might use it with a subscript; (^) pa[i] is identical to (^) *(pa+i). In short, an array-and-index expression is equivalent to one written as a pointer and offset. There is one difference between an array name and a pointer that must be kept in mind. A pointer

is a variable, so (^) pa=a and (^) pa++ are legal. But an array name is not a variable; constructions like a=pa and a++ are illegal. When an array name is passed to a function, what is passed is the location of the initial element. Within the called function, this argument is a local variable, and so an array name parameter is a pointer, that is, a variable containing an address. We can use this fact to write another version of strlen, which computes the length of a string.

int strlen(char *s) { int n; for (n = 0; *s != '\0', s++) n++; return n; }

Since (^) s is a pointer, incrementing it is perfectly legal; (^) s++ has no effect on the character string in the function that called (^) strlen, but merely increments (^) strlen's private copy of the pointer. That means that calls like

strlen("hello, world"); strlen(array); strlen(ptr);

all work. As formal parameters in a function definition,

char s[]; and char *s;

are equivalent; we prefer the latter because it says more explicitly that the variable is a pointer. When an array name is passed to a function, the function can at its convenience believe that it has been handed either an array or a pointer, and manipulate it accordingly. It can even use both notations if it seems appropriate and clear. It is possible to pass part of an array to a function, by passing a pointer to the beginning of the

subarray. For example, if (^) a is an array,

f(&a[2]) and f(a+2)

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

(i) Addition, multiplication and division of two pointers. (ii)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+ 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. (i) x = p++ is same as two expressions x = p followed by p = p + 1. (ii) x = (p)++ is same as two expressions x = p followed by p = p + 1. (iii) x=++p is same as two expressions p=p+1 followed by x=p. (iv) 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

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

indices, no other routine need know the name of the array, which can be declared (^) static in the source file containing implementations, the array may well not even have a name; it might instead be obtained by and thus alloc (^) andbe invisible outside (^) afree, it. In practical

calling (^) mallocor by asking the operating system for a pointer to some unnamed block of storage.

The other information needed is how much of (^) allocbuf has 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 ALLOCSIZE 10000 static char allocbuf[ALLOCSIZE]; static char *allocp = allocbuf; char *alloc(int n) { if (allocbuf + ALLOCSIZE - allocp>= n) { allocp += n; return allocp - n; } else return 0; } void afree(char *p) { if (p >= allocbuf&& p return p - s; }

In its declaration, (^) p is initialized to (^) s, that is, to point to the first character of the string. In the

while loop, each character in turn is examined until the (^) '\0' at the end is seen. Because (^) p

points to characters, (^) p++ advances (^) p to the next character each time, and (^) p-s gives the number of characters advanced over, that is, the string length. (The number of characters in the string

could be too large to store in an (^) int. The header (^) defines a type (^) ptrdiff_t that is large enough to hold the signed difference of two pointer values. If we were being cautious,

however, we would use (^) size_tfor the return value of (^) strlen, to match the standard library

version. (^) size_tis the unsigned integer type returned by the (^) sizeofoperator. Pointer arithmetic is consistent: if we had been dealing with (^) floats, which occupy more storage

that (^) chars, and if (^) p were a pointer to (^) float, (^) p++ would advance to the next (^) float. Thus we

could write another version of (^) allocthat maintains (^) floats instead of (^) chars, merely by changing

char (^) to (^) float throughout into account the size of the objects pointed to.The valid pointer operations are assignment ofallocand^ afree. All the pointer manipulations automatically take pointers of the same type, adding or subtracting a pointer and an integer, subtracting or comparing two pointers to members of the same array, and assigning or comparing to zero. All other pointer arithmetic is illegal. It is not legal to add two pointers, or to multiply or divide or shift or mask them, or to add (^) float or (^) double to them, or even, except for (^) void * , to assign a pointer of one type to a pointer of another type without a cast.

LECTUER NOTE 30

CHARACTER POINTERS AND FUNCTIONS

A string constant , written as "I am a string" is an array of characters. In the internal representation, the array is terminated with the null character (^) '\0' so that programs can find the end. The length in storage is thus one more than the number of characters between the double quotes. Perhaps the most common occurrence of string constants is as arguments to functions, as in printf("hello, world\n"); When a character string like this appears in a program, access to it is through a character pointer; printfreceives a pointer to the beginning of the character array. That is, a string constant is accessed by a pointer to its first element. String constants need not be function arguments. If pmessage is declared as

char *pmessage;

then the statement pmessage = "now is the time";

assigns to (^) pmessage a pointer to the character array. This is not a string copy; only pointers are involved. C does not provide any operators for processing an entire string of characters as a unit. There is an important difference between these definitions:

char amessage[] = "now is the time"; char *pmessage = "now is the time";

amessage is an array, just big enough to hold the sequence of characters and (^) '\0' that initializes

it. Individual characters within the array may be changed but (^) amessage will always refer to the

same storage. On the other hand, (^) pmessage is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents. We will illustrate more aspects of pointers and arrays by studying versions of two useful

functions adapted from the standard library. The first function is (^) strcpy(s,t) , which copies the

string (^) t to the string (^) s. It would be nice just to say (^) s=t but this copies the pointer, not the characters. To copy the characters, we need a loop. The array version first:

void strcpy(char *s, char *t) { inti; i = 0; while ((s[i] = t[i]) != '\0') i++;