3 Array Pointer and Structure
3 Array Pointer and Structure
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
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
*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;
*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
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
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
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
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