Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
198 views

3 Array Pointer and Structure

The document discusses various C programming concepts including arrays, pointers, structures, unions, and dynamic memory allocation. Specifically, it covers: - Arrays can store multiple elements of the same type and elements are accessed via indices. - Pointers store the address of other variables and can be used to access array elements. - Structures group together different data types under one name and can contain arrays. - Dynamic memory functions like malloc() and realloc() allocate and manage memory at runtime.

Uploaded by

AKASH PAL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
198 views

3 Array Pointer and Structure

The document discusses various C programming concepts including arrays, pointers, structures, unions, and dynamic memory allocation. Specifically, it covers: - Arrays can store multiple elements of the same type and elements are accessed via indices. - Pointers store the address of other variables and can be used to access array elements. - Structures group together different data types under one name and can contain arrays. - Dynamic memory functions like malloc() and realloc() allocate and manage memory at runtime.

Uploaded by

AKASH PAL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Chapter 3

Arrays, Pointers and Structures


LEARNING OBJECTIVES

 Arrays  Dynamic memory management


 Array initialization  Memory allocation function
 Passing array elements to function  Realloc
 Two dimensional arrays  Structures
 Syntax for 3D array declaration  Nesting of structures
 Pointers  Array of structures
 Pointer to pointer  Structures & functions
 Pointer to void (generic pointer)  Union
 Array of pointers  Declaration
 Pointer to function  Bit fields

arrays Example: int marks[6];


Here, ‘int’ specifies the type of variable, marks specifies name of
In C we have the following derived data types:
variable. The number 6 tells the dimension/size. The ‘[ ]’ tells the
• Arrays compiler that we are dealing with array.
• Pointers Accessing array elements: All the array elements are num-
• Structures bered, starting from 0, thus marks [3] is not the third, but the fourth
• Unions element.
Imagine a problem that requires to read, process, and print 10 Example: marks[2] – 3rd element
integers. We can declare 10 variables, each with different name. marks[0] – 1st element
Having 10 different names creates a problem; we need 10 read and We can use the variable as index.
10 write statements each for different variable. Thus marks[i] – ith element. As the value of i changes, refers dif-
ferent elements in array.
Definition
An array is a collection of elements of same data type. Array is a Summary about Arrays
sequenced collection. So, we can refer to the elements in array as 0th • An array is a collection of similar elements.
element, 1st element, and so on, until we get the last element. The • The first element in array is numbered 0, and the last element is
array elements are individually addressed with their subscripts/indi- one less than the total size of the array.
ces along with array name. We place subscript value in square brack- • An array is also known as subscripted variable.
ets ([ ]) followed by array name. This notation is called indexing. • Before using an array, its type and dimension must be
There is a powerful programming construct, loop, that makes declared.
array processing easy. It does not matter if there are 1, 10, 100 or • How big an array is, its elements are always stored in contiguous
1000 elements. memory locations.
We can also use a variable name in subscript, as the value of • Individual elements accessed by index indicating relative posi-
variable changes; it refers different elements at different times. tion in collection.
• Index of an array must be an integer.
Syntax of Array Declaration
Data_type array_name_[size]; Array Initialization
Here, data type says the type of elements in collection, array_name
is the name given to collection of elements and size says the num- Syntax
ber of elements in array. Data_type array_name[size] = {values};
Chapter 3  •  Arrays, Pointers and Structures  |  3.31

Example: Output:
int n[6]= {2,4,8,12,20,25}; // Array ini- 10 15 20 25 30
tialized with list of values
Here, we are passing the entire array by name. The formal
int num[10] = {2,4,12,20,35};
parameter to receive is declared as an array, so it receives
// remaining 5 elements are initialized with
entire array elements.
0
To pass the individual elements of an array, we have to
// values
int b[10] = {0}; // Entire array elements
use index of element with array name.
initialized with 0. Example: display (marks[ i ] ); sends only the ith element
Note: as parameter.
•• Till the array elements are not given any specific value, Example: A program to demonstrate call by reference:
they are supposed to contain garbage values. void main( )
•• If the number of elements used for initialization is lesser {
than the size of array, then the remaining elements are void display (int *);
initialized with zero. int marks[ ] = {5, 10 15, 20, 25};
•• Where the array is initialized with all the elements, men- display(&marks[0]);
tioning the dimension is optional. }
void display(int *p)
{
Array Elements in Memory int i;
Consider the following declaration – int num[5]. for(i = 0; i < 5; i++)
printf(“%d “,*(p+i));
What happens in memory when we make this declaration?
}
•• 10 bytes get received in memory, 2 bytes each for
5 integers. Output:
•• Since array is not initialized, all five values in it would be 5 10 15 20 25
garbage. This happens because the default storage class Here, we pass the address of very first element. Hence, the
is auto. If it is declared as static, all the array elements variable in which this address is collected (p) is declared as
would be initialized with 0. a pointer variable.
Note: Array elements are stored in contiguous memory
20012 20014 20016 20018 20020
location, by passing the address of the first element; entire
Note: In C, the compiler does not check whether the sub- array elements can be accessed.
script used for array exceeds the size of array.
Data entered with a subscript exceeding the array
size will simply be placed in memory out size the array, Two-dimensional Arrays
and there will be no error/warning message to warn the In C a two-dimensional array looks like an array of arrays,
programmer. i.e., a two-dimensional array is the collection of one-dimen-
sional arrays.
Passing array elements to function Example:  int x[4][2];
Array elements can be passed to a function by value or by
reference. 0 1

Example: A program to pass an array by value: 0


void main( ) 1
{
void display(int[ ]);// Declaration 2
int marks[ ] = {10,15,20,25,30}; 3
display (marks);// function call
} By convention, first dimension says the number of rows in
void display(int n[ ] )// function definition array and second dimension says the number of columns in
{
each row.
int i;
for(i = 0 ; i < 5 ; i++)
In memory, whether it is one-dimensional or a two-
printf(“%d “, n[ i ] ); dimensional array, the array elements are stored in one con-
} tinuous chain.
3.32 | Unit 3  •  Programming and Data Structures

The arrangement of array elements of a two-dimensional array in memory is shown below:


X [0][0] x [0][1] x [1][0] x [1][1] x [2][0] X [2][1] X [3][0] X [3][1]

6000 6002 6004 6006 6008 6010 6012 6014

Initialization Example:
We can initialize two-dimensional array as one-dimensional void main( )
array: {
int i, j, k;
int a[4] [2] = {0,1,2,3,4,5,6,7}
int arr [3] [3] [3] =
The nested braces can be used to show the exact nature {
of array, i.e., {11, 12, 13},
int a[4][2] = {{0,1},{2,3}{4,5},{6,7}} {14, 15, 16},
{17, 18, 19}
Here, we define each row as a one-dimensional array of },
two elements enclosed in braces. {21, 22, 23},
Note: If the array is completely initialized with supplied {24, 25, 26},
values, then we can omit the size of first dimension of an {27, 28, 29}
},
array (the left most dimension).
{31, 32, 33},
•• For accessing elements of multi-dimensional arrays, we {34, 35, 36},
must use multiple subscripts with array name. {37, 38, 39}
•• Generally, we use nested loops to work with multi- }
dimensional array. };
printf(“3D Array Elements \n”);
for (i = 0; i<3; i++)
Multidimensional Arrays {
C allows array of two or more dimensions and maximum for(j =0; j <3; j++)
numbers of dimensions a C program can have depends on {
the compiler, we are using. Generally, an array having one for (k= 0; k<3; k++)
dimension is called 1D array; array having two dimensions {
printf (“% d\t”, arr[i][j][k]);
is called 2D array and so on.
}
Syntax: printf (“\n”);
type array-name[d1] [d2] [d3] [d4]…[dn]; }
where dn is the size of last dimension. printf (“\n);
}
Example: }
int table[5][5][20];
Output:  3D Array Elements
float arr[5][6][5][6][5];
In our example array “table” is a 3D. (A 3D array is an array 11 12 13
of array of array) 14 15 16
17 18 19
Declaration and Initialization of 3D array
A 3D array can be assumed as an array of arrays; it is an 21 22 23
array of 2D arrays and as we know 2D array itself is an array 24 25 26
of 1D arrays. A diagram can help you to understand this. 27 28 29

31 32 33 2nd 2D array 31 32 33
21 22 23 1st 2D array 34 35 36
0th 2D array
37 38 39
11 12 13

14 15 16 Syntax for 3D Array Declaration


17 18 19 data–type array–name [table] [row] [column];
To store values in any 3D array, first point to table number,
Figure 1  3D array conceptual view row number and lastly to column number.
Chapter 3  •  Arrays, Pointers and Structures  |  3.33

Pointers Here, p, x and ch are pointer variables, i.e., variables capa-


ble of holding address. Since addresses are always whole
Pointer is a variable which contains address of another varia-
numbers, pointers would always contain whole numbers.
ble. C’s clever use of pointers makes it the excellent language.
The declaration float *x does not mean that x contains
Consider the declaration:
floating value, x will contain address of floating point vari-
int i = 3;
able. Similarly, ‘ch’ contains address of char value.
The declaration tells the C compiler to:
•• Reserve space in memory to hold in integer value.
•• Associate the name i with this memory location.
Pointer to Pointer
•• Store the value 3 at this location. We know, pointer is a variable that contains address of
another variable. Now this variable address might be stored
Memory map is: in another pointer. Thus, we now have a pointer that con-
i Location Name
tains address of another pointer, known as pointer to pointer.
Example:
3 Value at location void main()
{
2568 Location Number int i = 3, *p, **q;
(address)
p = &i;
q =&p;
Computer may choose different location at different times printf(“\n Address of i = %u”, &i);
for same variable. The important point is the address is a printf(“\n Address of i = %u”, p);
number. printf(“\n Address of i = %u”, *q);
The expression ‘&i’ gives the address of variable ‘i’. printf(“\n Address of p= %u”, &p);
p = &i; printf(\n Address of p= %u, q);
Assigns the address of ‘i’ to variable ‘p’. printf(“\n Address of q = %u”, &q)
The variable ‘p’ is declared as: printf(‘\n value of i= %d”,i);
printf(‘\n value of i= %d”,*(&i));
int *p;
printf(‘\n value of i= %d”,*p);
* tells the compiler that variable ‘p’ is an address variable. printf(‘\n value of i= %d”,**q);
Memory map of i, *p is – }

*p i
If the memory map is
2568 3 **q *p i
2720 2568 2010 2000 3

Now, pointer ‘p’ is referring to the variable ‘i’. 2050 2010 2000
The variable ‘i’ can be accessed in two ways: Then the output is:
•• By using the name of variable. Address of i = 2000
•• By using the pointer variable referring to location ‘i’. Address of i = 2000
Address of i = 2000
The operator ‘*’ can also be used along with pointer variable Address of p = 2010
in expressions. The operator ‘*’ acts as indirection operator. Address of p = 2010
Address of q = 2050
int x, *p; x ? p ? Value of i = 3
Value of i = 3
Value of i = 3
p = & x; x ? Value of p has
p Value of i = 3
Note: We can extend pointer to a pointer to pointer. In prin-
cipal, there is no limit on how far we can go on extending
*p = 4 x 4 Value of x has
p been changed this definition.

Usage of ‘p’ refers to value of ‘p’, where as ‘*p’ refers to Pointers for Inter-function Communication
value at the address stored in ‘p’, i.e., value of ‘i’. We know that functions can be called by value and called
by reference.
Example: int *p;
float *x; •• If the actual parameter should not change in called func-
char *ch ; tion, pass the parameter-by value.
3.34 | Unit 3  •  Programming and Data Structures

•• If the value of actual parameter should get changed in Operations can be Performed on Pointers
called function, then use pass-by reference. 1. Addition of a number to a pointer.
•• If the function has to return more than one value, return
Example: int i = 4, *j, *k;
these values indirectly by using call-by-reference.
j =&i;
Example: The following program demonstrates how to j = j +1;
return multiple values. k = j +5;

void main( ) 2. Subtraction of a number from a pointer.


{ Example: int i = 4, * j, * k;
void areaperi(int, int *, int *); j = &i; j = j −1;
int r; k = j – 3;
float a,p;
printf(“\n Enter radius of a circle”); 3. Subtraction of one pointer from another. One pointer
scanf(“%d”, &r); variable can be subtracted from another (provided both
areaperi(r, &a, &p); variables point to same array elements). The resulting
printf(“Area = %f”, a); value indicates the number of bytes (elements) separat-
printf(“\n Perimeter = %f”, p); ing (the corresponding array elements).
}
void areaperi(int x, int *p, int *q) Example:
{ void main ( )
*p = 3.14*x*x; {
*q = 2 * 3.14*x; int a[ ] = {5,10,15,20,25} ,*i, *j;
} i = &a[0];
Output: j = &a[4];
Enter radius of circle 5 printf(“%d, %d”, j−i,*j−*i);
Area = 78:500000 }
Perimeter = 31.400000 Output:  4, 20
Compatibility: Pointers have a type associated with them. The expression j-i prints 4 but not 8. because j and i pointing
They are not just pointer types, but rather are pointers to to integers that are 4 integers apart.
a specific type. The size of all pointers is same, which is 4. Comparison of two pointer variables. Pointer variables
equal to size of int. Every pointer holds the address of one can be compared provided both pointing to the same
memory location in computer, but size of variable that the data type.
pointer references can be different.
Notes: Do not attempt the following operations on pointers:
1. Addition of two pointers.
Pointer to Void (Generic Pointer) 2. Multiplication of a pointer with a number or another
A pointer to void is a generic type; this can point to any pointer.
type. Its limitation is that the pointed data cannot be refer- 3. Division of a pointer with a number or another pointer.
enced directly. Since void pointer has no object type, so its
length is undetermined; it cannot be dereference unless it
is cast. Important points about pointer arithmetic
•• A pointer when incremented always points to an immedi-
Example: The following example demonstrates generic
ately next location.
pointer.
•• A pointer when decremented always points to an element
void main ( ) precedes the current element.
{
int a = 10; Notice the difference with:
float x = 5.7; (*p)++
void *p; Here, the expression would have been evaluated as the value
p = &a; pointed by p increased by one. The value of p would not be
printf(“\n value of a = %d”, *((int*)p));
modified if we write
p= &x;
printf (“\n value of x = % f”, *((float *)p));
} *p++ = *q++;

Output: Because ++ has a higher precedence than *, both p and q


value of a = 10 are increased, but because both increase operators (++) are
value of x = 5.700000 used as postfix and not prefix, the value assigned to *p is
Chapter 3  •  Arrays, Pointers and Structures  |  3.35

*q before both p and q are increased. And then both are Example 4: Array of pointers pointing to 0th element of
increased, it would be equivalent to each row of a two-dimensional array
*p = *q int a[3][2] = {{1,2} {3,4}, {5,6}};
++p; int *p[3];
++q; p[0] = a[0]; p[1] =a[1];p[2] = a[2];

Implementation of arrays in C
Pointer to Function
Array name is the pointer to the first element in array. The
Function is a set of instructions stored in memory, so the
following discussion explains how pointers are used for
function also contains the base address. This address can
implementing arrays in C.
hold by using a pointer called pointer to function.
int n[ ] = {10,20,30,40,50};
Syntax:
n 10 20 30 40 50
5512 5514 5516 5518 5520 return_type (*function_pointer)(parameter –
list );
•• We know that mentioning the array name gets the base Example: int (*fp)(float, char, char);
address.
int *p = n;
Example:
// pointer to functions
Now ‘p’ points to 0 element of array ‘n’.
th
# include <iostream>
•• 0th element can be accessed as *array_ name. Using name space std;
int x = *n; int addition(int a, int b)
stores n[0] into ‘x’. {
•• we can say that *array _ name and *(array _ name+0) are return (a + b);
same. This indicates the following are same. }
num[i] int subtraction(int a, int b)
*(num + i) {
*(i+num) return (a – b) ;
}
(num is an array; i is an index)
int operation (int x, int y, int (*funtocall)
(int, int))
Array of Pointers {
The way there can be an array of ints or array of floats, sim- int g;
ilarly there can be an array of pointers. An array of pointers g = (*functocall)(x, y);
is the collection of addresses. return (g);
These arrays of pointers may point to isolated elements }
or an array element. int main( )
Example 1: Array of pointers pointing to isolated elements: {
int m, n;
int i = 5, j=10, k =15; int (*minus)(int, int) = substraction;
int *ap[3]; m = operation(7, 5, addition);
ap[0] = &i; ap[1] = &j; ap[2] = &k; n = operation(20, m, minus);
Example 2: Array of pointers pointing to elements of an cout < < n;
array: return 0;
int a[ ] = {0,20,45,50,70}; }
int *p[5], i ; In the example, minus is a pointer to a function that has two
for(i = 0; i <5 ; i++ ) parameters of type int. It is immediately assigned to point to
p[i] = &a[i] ; the function subtraction, all in a single line.
Example 3: Array of pointers pointing to elements of dif- Example:  Program to demonstrate function pointer
ferent arrays; int add(int, int);
int a[ ] = {5,10,20,25}; int sub(int, int);
int b[ ] = {0,100,200,300,400}; void main( )
int c[ ] = {50,150,250,350,450}; {
int *p[3]; Int (*fp) (int, int);
p[0] = a; p[1] = b; p[2]=c; fp = add;
3.36 | Unit 3  •  Programming and Data Structures

printf(“\n 4+5=%d”, fp(4,5)); Memory Allocation Function


fp = sub; •• Static memory allocation uses stack memory for variables.
printf (“\n 4 − 5 = %d”, fp(4,5)); •• Dynamic memory management allocates memory from
} heap.
int add(int x, int y)
{
The following are the four memory management functions
return x + y;
available in alloc.h and stdlib.h.
} 1. Malloc (Block memory allocation): Malloc function
int sub(int x,int y) allocates block of memory that contained the num-
{ ber of bytes specified in parenthesis. It returns ‘void’
return x – y; pointer to the first byte of allocated memory. The allo-
} cated memory is not initialized. If the memory alloca-
Output:  4 + 5 = 9 tion is not successful then it return NULL pointer.
4 – 5 = –1 Declaration
void *malloc (size_t size);
Pointer to structure  The main usage of pointer to structure The type size_t is defined as unsigned int in several
is we can pass structure as parameter to function as call by header files including stdio.h.
reference.
Syntax:  pointer = (type*) malloc(size );
The other usage is to create linked lists and other dynamic
data structures which depend on dynamic allocation. 2. Calloc (contiguous memory allocation): Calloc is
Consider the declaration primarily used to allocate memory for arrays. It initial-
struct employee izes the allocated memory with null characters.
{ Declaration:  void *calloc (size_t ele_count, size_t
char name[20]; ele_size);
Int age; Syntax:   ptr = (type*)calloc(ele-count,ele-size);
float salary; 3. Realloc (reallocation of memory): The realloc func-
}; tion is highly inefficient. When given a pointer to a
struct employee ∗ p; previously allocated block of memory, realloc changes
Variable of structures can be accessed using ‘.’ Operator (or) the size of block by deleting or extending the memory
→ operator that is at the end of block. If the memory cannot be extended,
(∗p).age = 20 ; (or) p → age = 20; then realloc allocates completely new block, copies the
(∗p).salary = 40, 231.0; (or) p → salary = 40,231.0; contents from existing memory location to new loca-
tion, and deletes the old location.
Dynamic Memory Management Declaration:  void *realloc (void *ptr, size_t new_
We can allocate the memory to objects in two ways—static size);
and dynamic allocation. Static memory allocation requires Syntax:  ptr = (type*)realloc(ptr, new_ size);
declaration and definition of memory fully specified in the 4. Free (Releasing memory): When the memory allo-
source program. The number of bytes required cannot be cated by malloc, calloc or realloc is no longer needed,
changed during run time. Dynamic memory allocation uses they can be freed using the function free( ).
predefined functions to allocate and de-allocate memory for Declaration:  void free(void *ptr);
data dynamically during the execution of program.
We can refer to dynamically allocated memory only Syntax:  free(ptr);
through pointers. Conceptual view of memory: Free function de-allocates complete memory referenced by
the pointer. Part of the memory block cannot be de-allocated.

Main( ) Functions Structures


Arrays are used to store large set of data and manipulate
Program memory
them but the disadvantage is that all the elements stored in
an array are to be of the same data type. When we require
using a collection of different data items of different data
Global Heap Stack types, we can use a structure.
Data Memory •• Structure is a method of packing data of different types.
•• A structure is a convenient method of handling a group of
Memory related data items of different data types.
Chapter 3  •  Arrays, Pointers and Structures  |  3.37

Syntax for declaration char address[20];


struct sturct_name char combination[3];
{ int age;
Data_type_1 var1; } newstudent;
Data_type_2 var2; printf (“ Enter student Information”);
: printf (“Enter student id – no”);
Data_type_n varn; scanf (“%d”, &newstudent.id_no):
}; printf (“ Enter the name of the student”);
scanf (“%s”, & newstudent.name);
Example: printf (“ Enter the address of the student”);
struct lib – books scanf (“%s”, &newstudent.address);
{ printf(“Enter the combination of the
char title [20]; student”)’;
char author[15]; scanf(“%s”, &newstudent.combination”);
int pages; printf (“ Enter the age of student);
float price; scanf (“%d “, &newstudent.age”);
}; printf (“ student information”);
The keyword struct declares a structure to hold the details printf (“ student id–no = %d”, newstudent.
of four fields namely title, author, pages and price, these are id – no);
printf(“student name = %s”, newstudent.
members of the structures.
name);
We can declare structure variables using the tag name printf(“student address = %s“, newstudent.
anywhere in the program. address);
Example: struct lib – books book1, book2, book3; printf (“students combination = %s”, newstu-
•• Declares book1, book2, book3 as variables of type struct dent. combination);
lib – books, each declaration has four elements of the printf(“Age of student = %d”, newstudent.
age);
structure lib– books.
}
Memory map of book1:

Book1 Title 20 bytes Nesting of Structures


Author 15 bytes The structures can be nested in two ways:
Pages 2 bytes
Price 4 bytes •• Placing the structure variable as a member in another
structure declaration.
•• Memory will not be allocated to the structure until it •• Declaration of the entire structure in another structure.
is instantiated. i.e., till the declaration of a variable to
Example:
structure.
struct date
•• To access the members of a structure variable, C provides
{
the member of (.) operator.
int day;
Example: To access author of book 1 – book1. author int month;
int year;
Syntax: structure_var.member_name;
};
•• The structures can also be initialized as any other variable struct student
of C. {
Example: struct lib-books book4={“Let us C”, int id–no;
“yashwanth”, 450, 200.95}; char name[20];
Note: The values must provide in the same order as they char address [20];
appear in structure declaration. int age;
•• One structure variable can be assigned to another struc- structure date doa;
ture variable. } oldstudent, newstudent;
•• Structure variables cannot be compared. The structure ‘student’ contains another structure date as
Example: one of its members.
# include <stdio.h> To access the day of date of admission (doa) of old stu-
void main( ) dent – oldstudent.doa.day.
{
Struct s1{ Example:
int id–no; struct outer
char name[20]; {
3.38 | Unit 3  •  Programming and Data Structures

int o1; Structures and Functions


float o2;
•• An entire structure can be passed as a parameter like any
struct inner
other variable.
{
•• A function can also return a structure variable.
int i1;
float i2; Example:
}; # include <stdio.h>
} out1, out2; struct employee
{
The innermost members in a nested structure can be int emp–id;
accessed by chaining all the concerned structure variables, char name[25];
from outermost to innermost; accessing i1 for out1-out1. char department[10];
inner.i1; float salary;
};
Array of Structures void main( )
{
It is possible to define an array of structures. For example, static struct employee emp1 = {
if we are maintaining information of all the students in the 12, “shyam”, “computer”, 7500.00};
college and if 100 students are studying in the college, we /* sending entire employee structure */
need to use an array than single variables. display(emp1);
}
Example: /* function to pass entire structure vari-
structure information able */
{ display(empf)
int id – no; struct employee empf
char name[20]; {
char address[20]; printf (“ %d %s % s %f”, empf.empid, empf.
char combination[3]; name, empf.department, empf.salary);
int age; }
}
student[100]; Union
Example: Union, like structure contains members whose individual
# include <stdio.h> data types may differ from one another. The members that
{ compose union all share the same storage area within the
struct info computer’s memory whereas each member within a struc-
{ ture is assigned its own unique storage area. Thus, unions
int id _ no; are used to conserve memory.
char name[20];
Declaration
char address[20];
char combination[3]; union item
int age; {
} int m;
struct info std[100]; float p;
int, i ,n; char c;
printf (“ Enter the number of students”); }Code;
scanf (“%d”, &n); This declares a variable code of type union item.
scanf(“Enter id–no, name, address, combina- The union contains three members each with a differ-
tion and age”); ent data type. However, we can use only one of them at a
for (i = 0; i<n; i ++) time. The compiler allocates a piece of storage that is large
scanf(“ %d %s %s %s %d”, &std[i].id_no, enough to access a union member; we can use the same syn-
std[i].name, std[i].address, tax that we use to access structure members, i.e.,
std[i]. combination,&std [i].age); Code.m
printf(“student information”); Code.p
for (i = 0 ; i < n; i ++) Code.c
printf(“%d %s %s % s % d”, std[i].id_no, are all valid member variables. During accessing, we should
std[i].name, std[i].address, std[i]. combi- make sure that we are accessing the member whose value is
nation, std[i]. age); currently stored.
Chapter 3  •  Arrays, Pointers and Structures  |  3.39

Example: U1.decval = 1000.5f;


union marks printf(“decval = %f pnum = %d my-value = % lf
{ “, U1. decval, U1.pnum, U1.my–value);
float perc; printf(“ U1 size = %d decval size =%d,
char grade; pnum size = %d my-value size = % d”,
} sizeof (U1), sizeof (U1.decval), sizeof
main( ) (U1.pnum), sizeof (U1.my-value));
{ }
union marks student1;
student1.perc = 98.5; Bit Fields
printf(“marks are %f address is %16ℓu”, stu- When a program variable ‘x’ is declared as int, then ‘x’ takes
dent1.perc, &student1. perc); the values from (-215) to (215 – 1), if x in the program takes
student1. grade = ‘c’; only two values, 1 and 0, which requires only one bit, then
printf(“grade is %c address is %16ℓu”, stu- the remaining 15 bits are waste.
dent1. grade, &student1. grade); In order to not to have this wastage, we can use bit fields
} with the several variables with the small enough maximal
values, which can pack into a single memory location
Example:
# include <stdio.h> Example:
void main ( ) struct student
{ {
Union u–example Int gender : 1 ; // gender takes only 0,1
{ values
float decval; Int marriage : 2 ; // marriage takes 4(0, 1,
int p-num; 2, 3) values
double my–value; Int marks : 7 ; // marks takes values from
}U1; 0 – 127
U1.my–value = 125.5; }
U1.pnum = 10;

Exercises
Practice Problems 1 (A) 30 (B) 22
Directions for questions 1 to 15:  Select the correct alterna- (C) 20 (D) Error
tive from the given choices. 2. main( )
{
1. Output of the following C program is char *ptr;
intF(int x, int *py, int **pz) ptr = “Hello World”;
{ printf(“%c\n”,*&*ptr);
int y, z; }
** pz+= 1; Output of the above program is
z = *pz; (A) Garbage value
*py+= 2; (B) Error
y = *py; (C) H
x+ = 3; (D) Hello world
return x+y+z; 3. #include <stdio.h>
} main( )
void main( ) {
{ register a =10;
int c, *b, **a ; char b[ ] = “Hi”;
c = 4; printf(“%s %d ”, b, a);
}
b = &c;
a = &b; Output is
printf( “%d”, F(c, b, a)); (A) Hi 10 (B) Error
} (C) Hi (D) Hi garbage value
3.40 | Unit 3  •  Programming and Data Structures

4. main ( ) for (j=i; j<4; ++j)


(D)
{ {
int fun( ) ; M[i][j] = temp;
(*fun)( ) ; temp = M[j][i];
} M[j][i] = M[i][j] ;
int fun( ) }
{ printf(“Hello”) ; 7. Consider the C program shown below:
} # include <stdio.h>
(A) Hello (B) Error # define print(a) printf(“%d”, a)
(C) No output (D) H int a;
5. Let B be a two-dimensional array declared as void z(int n)
B : array[1...10] [1...15] of integer; {
n += a;
Assuming that each integer takes one memory location
print (n);
the array is stored in row major order and the first ele-
}
ment of the array is stored at location 100, what is the
void x(int *p)
address of the element B[i] [j]?
{
(A) 15i + 10j + 84 (B) 15i + j − 16
int a = *p+2;
(C) 15i + j (D) 15i + j + 84
z(a) ;
6. Consider the following C program which is supposed *p = a;
to compute the transpose of a given 4 × 4 matrix M. print(a);
Note that, there is a Y in the program which indicates }
some missing statements. Choose the correct option to main(void)
replace Y in the program. {
# include <stdio.h>  a = 6;
int M[4][4] = { 8, 10, 9, 16, 12, 13, 11, x(&a);
15, 14, 7, 6, 3, 4, 2, 1, 5 }; print(a);
main( ) }
{ The output of this program is
int i, j, temp; (A) 14 8 6 (B) 16 6 6
for (i = 0; i<4; ++i) (C) 8 6 6 (D) 22 11 12
{
Y
8. Consider the program below:
} # include <stdio.h>
  for (i=0; i<4; ++i) int fun(int n, int *p)
  for (j=0; j<4; ++j) {
printf(“%d”, M[i] [j]); int x,y;
} if (n<=1)
(A) for (j=0; j<4; ++j) {
{ *p = 1;
M[j] [i] = temp; return 1;
temp = M[j][i]; }
x = fun(n-1, p);
M[j][i] = M[i][j];
y = x +p;
}
*p = x;
(B) for (j=0; j<4; ++j)
return y;
{
}
temp = M[j][i];
M[i][j] = M[j][i]; int main( )
M[j][i] = temp; {
} int a =15;
(C) for (j=i; j<4; ++j) printf( “%d\n”, fun(5, &a));
{ return 0;
temp = M[i][j];  }
M[i][j] = M[j][i]; The output value is
M[j][i] = temp; (A) 14 (B) 15
} (C) 8 (D) 95
Chapter 3  •  Arrays, Pointers and Structures  |  3.41

9. Consider the following C program segment main (int argc, char *argv[ ])
{
char p[20] ;
int i; int i;
char *s = “string” ; i = argv [1] + argv [2] − argv [3];
int l = strlen(s); printf ("%d", i);
for (i=0; i<l; i++) }
p[i] = s[l – i] ;
(A) 123 (B) 6
printf(“%s”, p) ;
(C) 0 (D) Error
The output of the program is
(A) string 13. The following C program is run from the command line
(B) gnirt as
(C) gnirts myprog one two;
(D) No output is printed what will be the output?
10. # include <stdio.h> main (int argc, char *argv [ ])
main( ) {
{ printf (“%c”,**++argv);
struct AA }
{ (A) m (B) o
int A = 5; (C) myprog (D) one
char name[ ] = “ANU”; 14. The following program
};
change(int *);
 struct AA *p = malloc(sizeof(struct
main( ) {
AA));
int a = 4;
printf(“%d”,p–>A);
change(a);
printf(“%s”,p–>name);
printf (“%d”, a);
}
}
Output of the program is change(a)
(A) 5 ANU int a;
(B) Runtime error {
(C) Compiler error printf(“%d”, a);
(D) Linker error }
11. The declaration Outputs
union u_tag { (A) 44 (B) 55
int ival; (C) 34 (D) 22
float fval;
15. What is the output of the following program:
char sval; main( )
} u;
{
denotes u is a variable of type u_tag and const int x = 10;
(A) u can have a value of int, float and char int *ptrx;
(B) u can represent either integer value, float value or ptrx = &x;
character value at a time *ptrx = 20;
(C) u can have a value of float but not integer printf (“%d”, x);
(D) None of the above }

12. If the following program is run from command line as (A) 5 (B) 10
myprog 1 2 3, what would be the output? (C) Error (D) 20
3.42 | Unit 3  •  Programming and Data Structures

Practice Problems 2 blue,


yellow = 1,
Directions for questions 1 to 11:  Select the correct alterna-
green
tive from the given choices.
};
1. The following program segment
int *i; assigns the value 1 to
*i = 10; (A) Red and Yellow
(A) Results in run time error (B) Blue
(B) Is a dangling reference (C) Red and blue
(C) Results in compilation error (D) Blue and yellow
(D) Assigns 10 to i 8. What would be the output of the following program?
2. A m × n matrix is stored in column major form. The sum = 0;
expression which accesses the (ij)th entry of the same for (i = −10; i < 0; i++)
matrix is sum = sum + abs(i);
(A) n × (j − 1) + i printf ("%d", sum);
(B) m × (j − 1) + i
(C) n × (m − 1) + ij (A) 100 (B) −505
(D) m × (n − 1) + j (C) 55 (D) −55
3. int ∗ S[a] is 1D array of integers, which of the follow- 9. An integer occupies 2 bytes of memory, float occupies
ing refers to the third element in the array? 4 bytes and character occupies 1 byte. A structure is
(A) ∗(S + 2) (B) ∗(S + 3) defined as:
(C) S + 2 (D) S + 3 struct tab {
4. If an array is declared as char a[10][12]; what is referred char a;
to by a[5]? int b;
(A) Pointer to 3rd Row float c;
(B) Pointer to 4th Row } table [10];
(C) Pointer to 5th Row Then the total memory requirement (in bytes) is
(D) Pointer to 6th Row (A) 14 (B) 70
5. The following code is run from the command line as (C) 40 (D) 100
myprog 1 2 3. What would be the output? 10. What are the values of u1 and u2?
main(int argc, char *argv[ ]) int u1, u2;
{ int x = 2;
int i, j = 0; int *ptr;
for (i = 1; i < argc; i++) u1 = 2*(x + 10);
j = j + atoi (argv [i]); ptr = &x;
printf (“%d”, j); u2 = 2*(*ptr + 10);
} (A) u1 = 8, u2 = 16
(B) u1 = 23, u2 = 24
(A) 123 (B) 6
(C) u1 = 24, u2 = 24
(C) Error (D) “123”
(D) None of the above
6. What will be the following C program output?
11. What is the output?
 main (int argc, char *argv[ ], char *env
func(a, b)
[ ]) {
int a, b;
int i;
{
for(i = 1; i < argc; i++)
return (a = (a = = b));
printf (“%s”, env[i]);
}
}
main ()
(A) List of all arguments {
(B) List of all path parameters int process(), func();
(C) Error printf(“The value of process is %d”, pro-
(D) List of environment variables cess (func,3,6));
7. The declaration }
process (pf, val1, val2)
enum colors {
int (*pf) ();
red,
Chapter 3  •  Arrays, Pointers and Structures  |  3.43

int val1, val2; (A) The value of process is 0


{ (B) The value of process is 3
return ((*pf) (val1, val2)); (C) The value of process is 6
} (D) Logical error

Previous Years’ Questions


1. Consider the following program in C language: void f1 (int a, int b)  {
# include < stdio. h> int c;
main () c=a; a=b; b=c;
{ }
int i; void f 2(int *a, int *b)  {
int *pi = &i;
int c;
scanf (“%d”, pi);
printf(“%d\n”, i + 5); c=*a; *a=*b; *b=c;
} }
Which one of the following statement is TRUE? int main ( ) {
 [2014] int a=4, b=5, c=6;
(A) Compilation fails f1 (a, b);
(B) Execution results in a run-time error f2 (&b, &c);
(C) On execution, the value printed is 5 more than printf(“%d”, c-a-b);
the address of variable i. }
(D) On execution, the value printed is 5 more than
4. What is the output of the following C code? Assume
the integer value entered.
that the address of x is 2000 (in decimal) and an inte-
2. Consider the following C function in which size is the ger requires four bytes of memory.[2015]
number of elements in the array E:
int main ( ) {
int MyX (int *E, unsigned int size)
unsigned int x[4] [3] =
{
int Y = 0;  { {1, 2, 3}, {4, 5, 6}, {7, 8, 9},
int Z; {10, 11, 12}};
int i, j, k;  printf (“%u, %u, %u”, x + 3, *(x +
for (i = 0; i < size; i++) 3), *(x + 2) + 3);
Y = Y + E[i]; }
for (i = 0; i < size; i++)
for (j = 1; j < size; j++) (A) 2036, 2036, 2036 (B) 2012, 4, 2204
{ (C) 2036, 10, 10 (D) 2012, 4, 6
Z = 0; 5. Consider the following function written in the C pro-
for (k = i; k < = j; k++) gramming language.[2015]
Z = Z + E[k]; void foo(char *a {
if (Z > Y) if ( *a && *a != ‘ ‘){
Y = Z; foo(a + 1);
} putchar(*a);
return Y; }
} }
The output of the above function on input “ABCD
The value returned by the function My X is the [2014]
EFGH” is
(A) maximum possible sum of elements in any sub -
array of array E. (A) ABCD EFGH (B) ABCD
(B) maximum element in any sub-array of array E. (C) HGFE DCBA (D) DCBA
(C) sum of the maximum elements in all possible 6. Consider the following C program segment.[2015]
sub-arrays of array E. #include <stdio.h>
(D) the sum of all the elements in the array E. int main()
3. The output of the following C program is ______ {
[2015] char s1[7] = “1234”, *p;
3.44 | Unit 3  •  Programming and Data Structures

p = s1 + 2; mystery(&c, &a);
*p = ‘0’;
mystery (&a, &d);
printf(“%s”, s1);
} printf(“%d\n”, a)
What will be printed by the program? }
(A) 12 (B) 120400 The output of the program is _____.
(C) 1204 (D) 1034 10. The following function computes the maximum value
7. Consider the following C program[2015] contained in an integer array p [ ] of size n (n > = 1).
#include<stdio.h> [2016]
int main ( ) int max (int *p, int n) {
{ int a = 0, b = n – 1;
static int a[ ] = {10, 20, 30, 40, while (_____) {
50}; if (p [a] < = p [b]) {a = a+1;}
static int *p[ ] = {a, a+3, a+4, else     { b = b – 1;}
a+1, a+2}; }
int **ptr = p; return p[a];
ptr++; }
printf(“%d%d”, ptr-p, **ptr); The missing loop condition is
} (A) a!=n
8. Consider the following C program. [2016] (B) b!=0
(C) b > (a +1)
void f (int, short);
(D) b!=a
void main( )
11. The value printed by the following program is ___.
{ [2016]
int i = 100; void f (int* p, int m) {
short s = 12; m = m +5;
short *p = &s; *p = *p + m;
_____; // call to f( ) return;
} }
Which one of the following expressions, when placed void main () {
in the blank above, will NOT result in a type checking
int i = 5, j = 10;
error?
(A) f (s,*s) (B) i = f (i,s) f(&i, j);
(C) f (i,*s) (D) f (i,*p) print f (“%d”, i +j);
9. Consider the following C program. [2016] }
# include<stdio.h> 12. Consider the following program:[2016]
void mystery (int *ptra, int *ptrb) { int f (int *p, int n)
int *temp; { if (n < = 1) return 0;
temp = ptrb; else return max (f (p +1, n – 1), p [0] – p [1] );
ptrb = ptra; }
ptra = temp; int main ()
{
} int a[ ] = {3,5,2,6,4};
int main ( ) { printf (“%d”, f(a,5));
int a = 2016, b = 0, c = 4, d = 42; }
mystery (&a, &b); Note: max (x,y) returns the maximum of x and y.
if (a < c) The value printed by this program is ______
Chapter 3  •  Arrays, Pointers and Structures  |  3.45

13. Consider the following C code: The decimal value closest to this floating-point num-
# include <stdio.h> ber is[2017]
int *assignval (int *x, int val) { (A) 1.45 × 101 (B) 1.45 × 10−1
*x = val; (C) 2.27 × 10−1 (D) 2.27 × 101
return x; 16. Match the following:
}
(P) static char var; (i) 
Sequence of memory loca-
void main ( ) { tions to store addresses
int *x = malloc (sizeof (int)); (Q) m = malloc (10); (ii) 
A variable located in data
if (NULL == x) return; m = NULL; section of memory
x = assignval (x, 0); (R) char *ptr [10]; (iii) Request to allocate a CPU
if (x) { register to store data
x = (int *) malloc (S) register int var1; (iv) A lost memory which cannot
(sizeof (int)); be freed
if (NULL == x) return;
x = assignval (x, 10); [2017]
} (A) P → (ii), Q → (iv), R → (i), S → (iii)
printf(“%d\n”, *x); (B) P → (ii), Q → (i), R → (iv), S → (iii)
free (x); (C) P → (ii), Q → (iv), R → (iii), S → (i)
} (D) P → (iii), Q → (iv), R → (i), S → (ii)
The code suffers from which one of the following 17. Consider the following function implemented in C:
problems:[2017] void printxy (int x, int y) {
(A) compiler error as the return of malloc is not type- int ptr;
cast appropriately x = 0;
(B) compiler error because the comparison should be ptr = &x;
made as x == NULL and not as shown y = ptr;
(C) compiles successfully but execution may result

ptr = 1;
in dangling pointer printf (“%d, %d” x, y);
(D) compiles successfully but execution may result }
in memory leak The output of invoking printxy (1, 1) is[2017]
14. Consider the following C program. (A) 0, 0 (B) 0, 1
(C) 1, 0 (D) 1, 1
# include <<stdio.h> 18. Consider the following snippet of a C program.
# include <<string.h> Assume that swap (&x, &y) exchanges the contents
void printlength (char *s, char *t)
 of x and y.
{ int main () {
unsigned int c = 0; int array[] = {3, 5, 1, 4, 6, 2};
int len = ((strlen(s) − strlen
 int done = 0;
(t)) > c) ? strlen (s) : strlen int i;
(t); while (done == 0) {
printf (“%d\n”, len); done = 1;
} for (i=0; i <=4; i++) {
void main ( ) { if (array[i] < array[i+1]) {
char *x = “abc”; swap(&array[i], &array[i + 1]) ;
char *y = “defgh”; done = 0;
printlength (x, y); }
} }
for (i=5; i >=l; i--) {
Recall that strlen is defined in string.h as returning
if (array[i] > array[i−l]) {
a value of type size_t, which is an unsigned int. the
swap(&array[i], & array[i−1]);
output of the program is _________.[2017]
done = 0;
15. Given the following binary number in 32-bit (single }
precision) IEEE-754 format: }
00111110011011010000000000000000 }
3.46 | Unit 3  •  Programming and Data Structures

printf{“%d”, array[3]); (A) 0, c


} (B) 0, a+2
The output of the program is ________.[2017] (C) ‘0’, ‘a+2’
19. Consider the following C Program. (D) ‘0’, ‘c’
#include<stdio.h> 2 1. Consider the following C program:
#include<string,h> #include<stdio.h>
int main () { void fun1 (char *s1, char * s2) {
char* c = “GATECSIT2017”; char *tmp;
char* p = c; tmp = s1;
printf{“%d”, s1 = s2
(int) strlen(c+2[p]-6[p]-1)) ; s2 = tmp;
return 0; }
} void fun2 (char **s1, char **s2) {
The output of the program is __________.[2017] char *tmp;
20. Consider the following C program. tmp = *s1;
#include<stdio.h> *s1 = *s2;
struct Ournode { *s2 = tmp;
}
char x, y, z;
int main () {
} ;
char *str1 = “Hi”, *str2 = “Bye”;
Int main () {
fun1 (str1, str2);
struct Ournode p = {‘1’, ‘0’, ‘a’+2};
printf (“%s %s “, str1, str2);
struct Ournode *q = &p; fun2 (&str1, &str2);
printf (“%c, %c”, *( (char*)q+1), printf (“%s %s”, str1, str2);
* ( (char*)q+2) ); return 0;
return 0; }
} The output of the program above is: [2018]
The output of this program is: [2018] (A) Hi Bye Bye Hi (B) Hi Bye Hi Bye
(C) Bye Hi Hi Bye (D) Bye Hi Bye Hi

Answer Keys
Exercises
Practice Problems 1
1. B 2. C 3. A 4. A 5. D 6. C 7. A 8. C 9. D 10. C
11. B 12. D 13. B 14. A 15. D

Practice Problems 2
1. B 2. B 3. A 4. D 5. B 6. D 7. D 8. C 9. B 10. C
11. A

Previous Years’ Questions


1. D 2. A 3.  -5 4. A 5. D 6. C 7. 140 8. D 9. 2016 10. D
11. 30 12. 3 13. D 14. 3 15. C 16. A 17. C 18. 3 19. 2 20. A
21. A

You might also like