You are on page 1of 112

Computer Programming

(CS F111)
Pointers and Arrays
BITS Pilani Dr. Lov Kumar, Dr. Sudeepta Mishra, Mr. Abhishek Thakur
Hyderabad Campus
Department of CSIS
Concept of Address and
Pointers
• Memory can be ADDR1 Contents1
conceptualized as a linear set ADDR2
of data locations. ADDR3
ADDR4
• Variables reference the ADDR5
contents of a locations ADDR6
*
• Pointers have a value of the *
*
address of a given location
ADDR11 Contents11

*
*

ADDR16 Contents16

2 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Fundamentals

• When a variable is defined, the


compiler (linker/loader actually) 00000000
allocates a real memory address
for the variable. x 00000000

 int x; will allocate 4 bytes 00000000


in the main memory, which 00000011
will be used to store an
integer value.
• When a value is assigned to a
variable, the value is actually
placed to the memory that was
allocated.
 x=3; will store integer 3 in
the 4 bytes of memory.
3 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Memory Address of a Variable

char ch = ‘A’;

ch:

0x2000 'A'
The memory
address of the The value of the
variable ch variable ch
4 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
The & Operator (Address of)

• Gives the memory address of an object

char ch = 'A';

0x2000 'A'
&ch yields the value 0x2000

• Also known as the “address-of ” operator


5 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Example:

char ch;
printf("%p", &ch);

“conversion specifier” for


printing a memory address

6 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


POINTERS

• Pointers are variables that contain memory addresses of


other variables
• A variable name directly references a value.
• A pointer indirectly references a value. Referencing a
value through a pointer is called indirection.
• A pointer variable must be declared before it can be
used.

7 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


POINTERS

Syntax : data_type *identifier

Note: The address operator cannot be applied to a constant or


an expression
Examples of pointer declarations:
int *a; // can also be written as int* a
float *b;
char *c;
FILE *fptr;
• The asterisk, when used as above in the declaration, tells the
compiler that the variable is to be a pointer, and the type of data
that the pointer points to.
8 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Notes on Pointers

• We can have pointers to any data type


Example: int* numPtr;
float* xPtr;

• The * can be anywhere between the


type and the variable
Example: int *numPtr;
float * xPtr;

9 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Pointers and the & Operator

Example:
char c = 'A';
char *cPtr;

cPtr = &c; Assigns the


address of c to cPtr

10 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example:

char* cPtr;
cPtr:
0x2004

Can store an address of


variables of type char

• We say cPtr is a pointer to char


11 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Example

A variable which can store


the memory address of
another variable
0x3A15

0x2000
cPtr

0x2002
0x1FFE 0x1FFF 0x2000 0x2001
etc
'A'
c
12 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Initializing Pointers

Correct Incorrect
int i, j; int y, z;
int *x,*y; z = &y; /* z is not a pointer variable, will
x=&i; /* address of i assigned to x */ give warning */
y=&j; /* address of j assigned to y */
int y;
float f = 4.5f; int *z;
float *fPtr = &f; z = y; /* z must reference y with
address operator, will give warning*/
double d = 3.14;
double *d1Ptr; int y;
d1Ptr = &d; char *c1;
c1=&y;
double *d2Ptr; /* c1 and y are not of the same type, will
d2Ptr = d1Ptr; give a warning */

13 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Notes on Pointers (cont.)

Beware of pointers
int *numPtr; which are not
initialized!

???
numPtr

14 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Notes on Pointers (cont.)

• When declaring a pointer, it is a good


idea to always initialize it to NULL
(a special pointer constant)
• NULL is a macro and denotes the null
pointer constant

int *numPtr = NULL;

NULL
numPtr

15 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Initializing Pointers

Like other variables, always initialize pointers


before using them!!!
For example:
int main(){
int x;
int *p;
scanf("%d", p); /* Don’t */
p = &x;
scanf("%d", p); /* Correct */
}

16 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Initializing Pointers

int main()
{ You do not end up
int *p; assigning a value to the
scanf("%p",&p); memory location
printf("%p",p);
Gives segmentation
*p=10; fault
printf("%d",*p);
}

17 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


The * Operator (Value At)

• Allows pointers to access variables they point to.


• Also known as “dereferencing/ indirection operator”
• Should not be confused with the * in the pointer
declaration

18 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Pointers and the  Operator

Example: char c = 'A';

char *cPtr = NULL;

cPtr = &c; Changes the value of the


variable which cPtr points to
*cPtr = 'B';

c: cPtr:
B
A 0x2000
0x2000

19 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Easy Steps to Pointers (1/4)

Step 1: Declare the variable to be pointed to

int num;
char ch = 'A';
float x;

num:
ch: ‘A’
x:

20 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Easy Steps to Pointers (cont)
2/4

Step 2: Declare the pointer variable


numPtr: NULL

int num; chPtr: NULL


char ch = ‘A’;
float x; xPtr: NULL
int* numPtr = NULL;
char *chPtr = NULL; num:
float * xPtr = NULL;
ch: ‘A’
x:

21 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Easy Steps to Pointers (cont)
3/4
Step 3: Assign address of variable to pointer
int num; numPtr: addr of num
char ch = ‘A’;
float x; chPtr: addr of ch
int* numPtr = NULL;
char *chPtr = NULL; xPtr: addr of x
float * xPtr = NULL;
numPtr = #
chPtr = &ch; num:
xPtr = &x;
ch: ‘A’

A pointer’s type has to correspond to the type of x:


the variable it points to

22 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Easy Steps to Pointers (cont)
4/4
Step 4: De-reference the pointers
int num;
char ch = ‘A’; numPtr: addr of num

float x;
chPtr: addr of ch
int* numPtr = NULL;
char *chPtr = NULL; xPtr: addr of x
float * xPtr = NULL;
numPtr = #
chPtr = &ch; num: 65
xPtr = &x;
ch: ‘A’
*xPtr = 0.25;
*numPtr = *chPtr; x: 0.25

23 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Multiple pointers to same
variable

pa 0X2000 a 10 ptra 0X2000

0X1000 0X2000 0X1200

pa
a 10

0X2000

ptra

24 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Chain of pointers (Multiple
Indirections)
x p1 p2
100 0x1000 0x2000
0x1000 0x2000 0x2200

#include <stdio.h>
int main()
If you write int *p2 instead of int **p2,
{ then you will get a warning and
int x, *p1,**p2; printf(“%d”, **p2);
x=100; will give error.
p1=&x;
p2=&p1;
printf(“%d”, **p2);

return 0;
}

25 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


What's the difference between the following
declarations.
A. int *x;
B. int* x;
C. int * x;

What is the ouptut?


int j = 3;
int *ip;
ip = &j;
*ip = 7;
printf(“%d\n %d”, j, *ip);

26 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


sizeof() Operator

It returns size of any data-type in bytes.

Ex: sizeof(int) = 4 bytes


sizeof(char) = 1 bytes
sizeof(double) = 8 bytes
sizeof(short) = 2 bytes
sizeof(float) = 4 bytes
Ex :
int a = 10; char ch = ‘a’;
int *pa = &a; char *pch = &ch;
sizeof(pa); // 4 or 8 bytes sizeof(pch); // 4 or 8 bytes
27 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Predict Output

int i = 2, j = 3, k;
k = sizeof(++i + ++j); // sizeof() returns 4 or 8 (bytes)
printf(“%d %d %d”, i, j, k);

Output : 2 3 4
sizeof() operator doesn't evaluate the expression, it just
replaces variable with its type so ++i is not evaluated.

28 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Pointer Arithmetic

• type *a;

(i) addition :
constant(k) : a + k => a + k*sizeof(type)

Ex : int b = 10;
int *a = &b; // address of b is 1000
a = a + 2;
printf(“%p\n”, a); // output is 1008

29 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Pointer Arithmetic

(ii) subtraction:
An integer can be subtracted from a pointer variable

Ex : int b = 10;
int *a = &b; // address of b is 1008
a = a - 2;
printf(“%p\n”, a); // output is 1000

30 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


What not allowed

 Adding two pointers p1 + p2; // incorrect


 Multiplying two pointers p1 * p2; // incorrect
 Division not allowed p1 / p2; // incorrect

 p1 = p1 – p2 * 10; // incorrect
 p1 = p2 / 5; // incorrect

31 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Comparing pointers

• relational operator (<, <=, >, >=, !=, ==)


• Meaningful only when both pointer points to same datatype
• Outcome depends upon on the relative position of the variables

For Ex :
p = &a;
q = &b;
p <= q
p >= q
Ex. p == NULL
p != q

32 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


void pointer

• A void pointer is a special type of pointer that can point


to any data type.

• Syntax
void *data_type;

 Generic Pointer
 It is valid to assign address of any variable to void *
variable & vice versa
 Casting is not required while performing assignment to
void *
 Cannot use indirection operator on void *
33 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
example

34 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


const keyword

 const variable : Cannot change the value of the variable.

const int a = 5;
a += 5; // error

 Pointer to a constant :

const data-type *ptr;


or
data-type const *ptr;

35 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


pointer to a Constant

36 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


pointer to a Constant

#include<stdio.h>

int main()
{
int a = 5;
const void *ptr;
ptr = &a;
printf("%p\n",ptr);
printf("%d\n",*((int *)ptr));
*((int *)ptr) = 100; // does not cause error
*ptr = 200; // causes error
a++;
printf("%d\n",*((int *)ptr));
return 0;
}

37 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


pointer to a Constant

#include<stdio.h>

int main()
{
int a = 5;
const int *ptr;
ptr = &a;
printf("%p\n",ptr);
ptr++;
printf("%p\n",ptr);
return 0;
}

OUTPUT:
0x7fff529f8be8
0x7fff529f8bec
38 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
constant pointer to Variable

data-type *const ptr; ptr++ will also


cause error

39 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


constant pointer to Variable

data-type *const ptr;

#include<stdio.h>

int main()
{
int a = 5;
float b = 20;
void *const ptr = &a;
ptr = &b;
return 0;
}

error: cannot assign to variable 'ptr'


with const-qualified type 'void *const'

40 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


constant pointer to constant
const data-type *const ptr;

41 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


constant pointer to constant

#include<stdio.h>
ptr++; will also cause error
int main()
{
int i = 10;
int j = 20;
const void *const ptr = &i;
printf("ptr: %d\n", *(int *)ptr);
ptr = &j;
*ptr = 100;
return 0;
}
error: cannot assign to variable 'ptr' with error: read-only variable is not
const-qualified type'const void *const’ assignable
ptr = &j *ptr = 100;

42 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Function returning a pointer

int *process(int x, int y)


{
int *p;
…….
return p;
}

int main()
{
int a, b;
int *px;
px = process(a, b);
return 0;
}

43 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Passing functions to other
functions
int process(int (*)(int, int)); int funct1(int a, int b)
int funct1(int, int); {
int funct2(int, int); int c;
c = ….
int main()
return c;
{
}
int i, j;
int funct2(int x, int y)
i = process(funct1);
{
j = process(funct2);
int z;
}
z = …..;
int process(int (*pf)(int, int)) return z;
{ }
int a, b, c;
c = (*pf)(a, b);
return c;
}
44 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
45 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Why Do We Need Arrays?
• There are 800 salaried employees in a
company. You need to read the 800 salaries
from the input, compute the average salary,
and determine how many employees are paid
above average..
• You cannot possibly compute all this while reading the
salaries from the input. The 800 salaries must be stored
somewhere.
• Maybe you can do this?
• double salary1, salary2, ..., salary800;
• X But these variables cannot be processed in a loop!
• Solution: Arrays!
46 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Data Types

Data Types

(2) (3)
(1)

Primitive User-defined
Derived Types
Types Types

-Arrays -int -Structures


-Pointers -float -Unions
-char -Enumerations

Data Structure: Arrays, Structures, Lists, Stacks, Trees etc.

47 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Arrays

• Array is a data structure which can represent a collection of


data items which have the same data type (float/int/char)

• All the data items constituting the group share the same name.
int x[10];
• Individual elements are accessed by specifying the index.

48 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Declaring Arrays

• Like variables, the arrays that are used in a program must be


declared before they are used.

• General syntax:
type array-name [size];
– type specifies the type of elements that will be contained in
the array (int, float, char, etc.)
– size is an integer constant which indicates the maximum
number of elements that can be stored inside the array.

int marks[5];
– marks is an array containing a maximum of 5 integers.

49 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Declaring Arrays

Examples:
int x[10];
char line[80];
float points[150];
char name[35];

• If we are not sure of the exact size of the array, we can define an
array of a large size.
int marks[50];
though in a particular run we may only be using, say, 10
elements.

50 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


How an array is stored in memory?

• Starting from a certain memory location, the successive array


elements are allocated space in consecutive memory locations.
int a[10];

a[0] a[1] a[2] a[9]

51 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Access a particular element

• A particular element of the array can be accessed by


specifying two things:
– Name of the array.
– Index (relative position) of the element in the array.
• In C, the index of an array starts from zero.
• Example:
– An array is defined as int x[10];
– The first element of the array x can be accessed as x[0],
fourth element as x[3], tenth element as x[9], etc.

52 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Warning

In C, while accessing array elements, array bounds are


not checked.
• Example:
int marks[5];
:
:
marks[8] = 75;
– The above assignment would not necessarily cause an error.
– Rather, it may result in unpredictable program results.

• No checking!
• C is an UNSAFE language!

53 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Initialization of Arrays
• General form:
type array_name[size] = { list of values };
size should be an integer constant
• Examples:
int marks[5] = {72, 83, 65, 80, 76};
char name[4] = {‘A’, ‘m’, ‘i’, ‘t’};
• Some special cases:
– If the number of values in the list is less than the number of
elements, the remaining elements are automatically set to zero.
float total[5] = {24.2, -12.5, 35.1};

total[0] = 24.2, total[1] = -12.5, total[2] = 35.1, total[3] = 0.0,


total[4] = 0.0

54 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Initialization of Arrays

• The size may be omitted. In such cases the compiler


automatically allocates enough space for all initialized
elements.
int flag[] = {1, 1, 1, 0};
char name[] = {‘A’, ‘m’, ‘i’, ‘t’};

• NOTE! The following are illegal:


int my_array[5];
my_array = { 1, 2, 3, 4, 5 }; /* WRONG */

int my_array[5];
my_array[5] = { 1, 2, 3, 4, 5 }; /* WRONG */

55 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Predict Output

more examples on Initialization:


#include <stdio.h>
int main()
{
int i;
int max[5] = {8,7};
for (i=0;i<=7;i++)
printf ("%d\n", max[i]); 8
return 0; 7
0
}
0
0
5
-1076194544
-1076194472

56 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


How to read the elements of an array?

• By reading them one element at a time


for (j=0; j<25; j++)
scanf (“%f”, &a[j]);
• The ampersand (&) is necessary.
• The elements can be entered all in one line or in
different lines.

57 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


How to print the elements of an array?

• By printing them one element at a time.


for (j=0; j<25; j++)
printf (“\n %f”, a[j]);
– The elements are printed one per line.
printf (“\n”);
for (j=0; j<25; j++)
printf (“ %f”, a[j]);
– The elements are printed all in one line (starting with a
new line).

58 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Ex 1: Input the marks of 10 students and print it

59 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Ex 2 : Avg Marks of n students

60 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Ex 3 : Print All Employees whose salary > avg
Salary

61 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example 4 : Find maximum

62 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example 5

• Write a C program to copy elements of an array A


into another array B so that following sequences
should be followed:
– All even elements of A from left to right are copied into B
from left to right.
– All odd elements of A from left to right are copied into B
from right to left.
Ex : Input :
9 10 11 6 8 5 1 20

Output:
10 6 8 20 1 5 11 9

63 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example 5

64 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example 6 : Binary Equivalent

65 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Caution
• You cannot
 use = to assign one variable to another.
int a[10], b[10];
a = b; // incorrect you can’t copy b into a

How to copy then ?


for(i=0; i<n; ++i)
a[i] = b[i];

 use == to directly compare array variables


if(a == b) { … }

 directly scanf and printf arrays


printf(“….”, a);

 int a[5] = {1,2,3, , }; //incorrect, gives compilation error

66 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Arrays & Pointers

Subtraction :
a.) constant(k) : a – k => a – k * sizeof(type)

b.) if 2 pointers point to same array then subtraction is


allowed. The answer is an integer
a:

int a[7];
int *q = &a[4];
int *p = &a[0];
int k = (q – p); // k = (q - p) / sizeof(type)
printf("k = %d\n", k);

CS F111 BITS Pilani, Hyderabad Campus


Arrays & Pointers

int a[10];

int *pa;
pa = &a[0];

CS F111 BITS Pilani, Hyderabad Campus


Arrays & Pointers

pa+1, pa+2, …

*(pa+1) a[1]

*(pa+2) a[2]

CS F111 BITS Pilani, Hyderabad Campus


Arrays & Pointers

#include<stdio.h>

int main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int *pa = &a[0];
for(int i = 0;i<10;i++)
printf("%d %p\n",*(pa+i),pa+i);
}
Output:
1 0x7fff578b5bc0
2 0x7fff578b5bc4
3 0x7fff578b5bc8
4 0x7fff578b5bcc
5 0x7fff578b5bd0
6 0x7fff578b5bd4
7 0x7fff578b5bd8
8 0x7fff578b5bdc
9 0x7fff578b5be0
CS F111 BITS Pilani, Hyderabad Campus
Arrays & Pointers

Note : Name of an array is synonym for the location of


the initial element. It’s actually constant pointer

pa = &a[0] pa = a;

Hence a[i] *(a+i) *(i+a) i[a]

CS F111 BITS Pilani, Hyderabad Campus


Arrays & Pointers

#include<stdio.h>

int main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int *pa = a;
for(int i = 0;i<10;i++)
printf("%d %p\n",*(a+i),a+i);
}
Output:
1 0x7fff578b5bc0
2 0x7fff578b5bc4
3 0x7fff578b5bc8
4 0x7fff578b5bcc
5 0x7fff578b5bd0
6 0x7fff578b5bd4
7 0x7fff578b5bd8
8 0x7fff578b5bdc
9 0x7fff578b5be0
CS F111 BITS Pilani, Hyderabad Campus
Arrays & Pointers

#include<stdio.h>

int main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
for(int i = 0;i<10;i++)
printf("%d %p\n",i[a], &i[a]);
}

Output:
1 0x7fff578b5bc0
2 0x7fff578b5bc4
3 0x7fff578b5bc8
4 0x7fff578b5bcc
5 0x7fff578b5bd0
6 0x7fff578b5bd4
7 0x7fff578b5bd8
8 0x7fff578b5bdc
9 0x7fff578b5be0
CS F111 BITS Pilani, Hyderabad Campus
Arrays & Pointers

#include<stdio.h>
int main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int *pa = &a[9];
for(int i = 9;i>=0;i--)
printf("%d\n",pa[-i]);
}
Output:
1
2
3
4
5
6
7
8
9
10
CS F111 BITS Pilani, Hyderabad Campus
Pass 1D Arrays as Function
argument
• You need to declare array_name and number of
elements in the array as formal argument.
• To call such function you need to pass array_name
and number of elements in the function call.

For Ex : a function declaration of some function


accepting an array is :
void someFunction(int a[], int n);
OR
void someFunction(int *a, int n);

75 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Arrays in function

CS F111 BITS Pilani, Hyderabad Campus


Example 1

• Write a function to pass a 1D integer array and calculate the


sum of all elements.

77 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example 2

#include<stdio.h>

void print (int *a,int n)


{
for(int i = 0;i<n;i++)
printf("%d\n",a[i]);
}
int main()
{
int a[5] = {1,2,3,4,5};
int b[10] = {1,2,3,4,5,6,7,8,9,10};
print(a,5);
print(&b[5],5);
}

78 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


limits.h
Macro Value Description
CHAR_BIT 8 Defines the number of bits in a byte.
SCHAR_MIN -128 Defines the minimum value for a signed char.
SCHAR_MAX +127 Defines the maximum value for a signed char.
UCHAR_MAX 255 Defines the maximum value for an unsigned char.
Defines the minimum value for type char and its value will be
CHAR_MIN -128 equal to SCHAR_MIN if char represents negative values,
otherwise zero.
Defines the value for type char and its value will be equal to
CHAR_MAX +127 SCHAR_MAX if char represents negative values, otherwise
UCHAR_MAX.
SHRT_MIN -32768 Defines the minimum value for a short int.
SHRT_MAX +32767 Defines the maximum value for a short int.
USHRT_MAX 65535 Defines the maximum value for an unsigned short int.
INT_MIN -2147483648 Defines the minimum value for an int.
INT_MAX +2147483647 Defines the maximum value for an int.
UINT_MAX 4294967295 Defines the maximum value for an unsigned int.
LONG_MIN -9223372036854775808 Defines the minimum value for a long int.
LONG_MAX +9223372036854775807 Defines the maximum value for a long int.
ULONG_MAX 18446744073709551615 Defines the maximum value for an unsigned long int.
79 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
limits.h

80 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example 2 : Find 3rd smallest in an
array

81 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Disadvantages of Arrays

• Wastage of memory
• Consecutive space might be unavailable
• Operation like insertion and deletion is time
consuming

82 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


83 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Why 2D Arrays ???

• Lots of Real world data is stored in form of table.


• A table is an entity having rows and columns

• Ex :
• Profit or sales chart of companies
• Point table of a series (in Cricket, football etc…)
• Movie ratings by multiple reviewers

84 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Why 2D Arrays ???

• Relationship between objects can


be captured by 2D arrays.
• ex : cities connected by roads, friendship relationship
where it captures the how strong is the relation among
friends.

85 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Why 2D Arrays ???

• Used quite often in Maths especially Matrices and


it's manipulation.

4 9 0
13 -10 2
A= similarly you have matrices B,C
5 3 7
10 0 -3

And you can be asked to find A + B, A X B or det(A) or


inv(A)

86 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Two Dimensional Arrays

• Many applications require us to store a table of


values.
• Ex : Product rating by customers

Product
0 1 2 3

customer 0 4 3 5 1
1 3 5 4 2
2 5 4 2 5

87 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Declaring 2-D Arrays

• C allows us to define such tables of items by using


two-dimensional arrays.
General form:
type array_name[NoOfRows][NoOfColumns];

Examples:
int rating[3][4];
int marks[5][10];
float profit[12][25];
double matrix[100][100];

88 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Accessing Elements of a 2-D Array

• Uses two indices to access the element


– First index is called row index
– Second index is called column index
– Both the indices should be expressions which evaluate to
integer values
– Example :
rating[i][j] = 5;
arr[m+6*n][n%8] = 5;

89 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


How is a 2-D array is stored in memory?

How is 2D array stored in RAM

•Row-major order : arranged in a linear array in row


ordered manner i.e. first row1 then row2 and so on.

How to calculate index in 1D representation for any cell in 2D


array with rIndex = i and cIndex = j
Index in 1D memory = (i * C + j) where C is number of columns
in 2D array

90 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


How is a 2-D array is stored in memory?

How is 2D array stored in RAM

•Column-major order : arranged in a linear array in


column ordered manner i.e. first col1 then col2 and so on.

How to calculate index in 1D representation for any cell in 2D


array with rIndex = i and cIndex = j
Index in 1D memory = (j * R + i) where R is number of rows in
2D array
91 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Initialization of 2D arrays

int my_array[2][3]; /* not initialized */


int my_array[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; /* OK */
int my_array[2][3] = { 1, 2, 3, 4, 5, 6 };
int arr[2][]= { { 1, 2, 3 }, { 4, 5, 6 } }; /* invalid */
int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; /* invalid */
int arr[][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; /* OK */
int my_array[][3] = { 1, 2, 3, 4, 5, 6 };
int my_array[][3] = { { 1, 2, 3 }, { 4, 5 } }; /* OK; missing value = 0 */
int my_array[][3] = { 1, 2, 3, 4, 5, 6, 7, 8 }; /* OK; missing value = 0 */
int my_array[][3] = { { 1, 2, 3 }, { 4, 5 },{} }; /* OK; missing values = 0 */

Rule : No. of columns must be specified.

92 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Two dimensional arrays
int arr[2][3];
int i, j;
int sum = 0;
arr[0][0] = 1;
arr[0][1] = 23;
arr[0][2] = -12;
arr[1][0] = 85;
arr[1][1] = 46;
arr[1][2] = 99;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
sum += arr[i][j];
}
}
printf("sum = %d\n", sum);
93 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
How to read the elements of a 2-D array?

• By reading them one element at a time


for (i=0; i<nrows; i++)
for (j=0; j<ncols; j++)
scanf (“%f”, &a[i][j]);

• The ampersand (&) is necessary.

• The elements can be entered all in one line or in different lines.

• No. of rows and columns both must be specified in array


declaration.

• Name of 2D array points to the first element of the first row.

94 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example
• A program to input marks of 5 students in 10 subjects each and
display the marks.

95 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example : Matrix Addition

96 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example : Matrix Mulitplication

97 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example : Matrix Mulitplication (contd…)

98 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Example : Matrix Mulitplication (contd…)

99 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


2D arrays & pointers

int B[2][3] = {1,2,3,4,5,6};


• name of array is a pointer to the 1st 1D array

*B  address of B[0] i.e., &B[0]


B  *B  &B[0]  &B[0][0]
**B  value of B[0][0]
B + 1  B + 1 * size of 1D array of 3 integers  gives address of B[1]
*(B+1)  &B[1]  &B[1][0]
*(B+1)+2 ??  &B[1][2]
*(*B+1) ??  B[0][1] = 2

100 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


2D arrays & pointers

int B[2][3] = {1,2,3,4,5,6};

B[i][j]  *(B[i] + j)  *(*(B + i) + j)

101 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


2D arrays & pointers

int B[2][3] = {1,2,3,4,5,6};


int *p = B; What does this mean?

B is a pointer to a 1D array of 3 integers, gives warning

Defining a pointer to a 1D array of 3 integers

int (*p)[3] = B;
102 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
Pass 2D array as Function
argument
You have to mention column size in the 2D array parameter

103 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Pass 2D array as Function
argument
#include <stdio.h> int main(void)
{
int a[2][2] = {1,2,3,4};
void PrintMyArray(int *array, int row, int col) int i,j,row = 2,col = 2;
{
int i,j; PrintMyArray(&a[0][0],row,col);
for(i =0 ;i<row; i++)
{ PrintMyArray(a[0],row,col);
for(j=0;j<col;j++)
{ return 0;
printf("array[%d][%d]=%d\n",i,j,array[i*col+j]); }
}
}
}

104 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Pass 2D array as Function
argument
#include <stdio.h> void ptr_to_array_ver(int (*arr)[COLS])
#define ROWS 4 {
#define COLS 3 int i, j;
for (i = 0; i < ROWS; i++)
void ptr_to_array_ver(int (*arr)[COLS]);
{
int main () for (j = 0; j < COLS; j++)
{ {
int matrix[ROWS][COLS] = {{1, 2, 3}, printf("%d\t", (*arr)[j]);
{4, 5, 6}, }
{7, 8, 9}, arr++;
{10, 11, 12}}; printf("\n");
printf("Printing Array Elements: \n");
}
ptr_to_array_ver(matrix);
return 0;
}
}

105 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Dynamic Arrays

int r,c;
scanf(“%d %d”, &r, &c);
int a[r][c]; // dynamic allocation

data-type fnName(int r, int c, int a[][c]); //fn decl

•You need to pass first row then column and then array
name

106 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Pass 2D dynamic array as Fn
argument
You have to mention the dimension first and then the
array argument.

107 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Total & Max Profit of a company

108 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Sort columns in 2D array

109 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Practice Problems

1. Given a 2D array of size m*n having integers and a integer x.


Find in which row and column is the number present.
2. Given a 2D array of size n*n. Transpose it and print it
3. Given a 2D array of size m*n. Print the sum of individual rows
and sum of individual column.
4. Given a 2D array sort rows of the 2D array.

110 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus


Harder Problems
1. Transpose a 2D array of size n*n without using separate 2D array.
2. Read a number n and use a 2D array to print the following pattern.
for ex. n = 4 , output is :
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
3. Use 2D array to calculate a Pascal Traingle and hence find the nCr
value. for n = 4, your pascal triangle is
1
11
121
1331
14641
now 4C2 = 6 i.e. a[4][2] gives you the answer.
111 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus
THANK YOU

112 8/14/2018 CS F111 BITS Pilani, Hyderabad Campus

You might also like